Task description

A non-empty zero-indexed array A consisting of N integers is given. The consecutive elements of array A represent consecutive cars on a road.

Array A contains only 0s and/or 1s:

  • 0 represents a car traveling east,
  • 1 represents a car traveling west.

The goal is to count passing cars. We say that a pair of cars (P, Q), where 0 ≤ P < Q < N, is passing when P is traveling to the east and Q is traveling to the west.

For example, consider array A such that:

A[0] = 0 A[1] = 1 A[2] = 0 A[3] = 1 A[4] = 1

We have five pairs of passing cars: (0, 1), (0, 3), (0, 4), (2, 3), (2, 4).

Write a function:

class Solution { public int solution(int[] A); }

that, given a non-empty zero-indexed array A of N integers, returns the number of pairs of passing cars.

The function should return −1 if the number of pairs of passing cars exceeds 1,000,000,000.

For example, given:

A[0] = 0 A[1] = 1 A[2] = 0 A[3] = 1 A[4] = 1

the function should return 5, as explained above.

Assume that:

  • N is an integer within the range [1..100,000];
  • each element of array A is an integer that can have one of the following values: 0, 1.

Complexity:

  • expected worst-case time complexity is O(N);
  • expected worst-case space complexity is O(1), beyond input storage (not counting the storage required for input arguments).

Elements of input arrays can be modified.

Solution

 
Programming language used: Java
Code: 02:08:07 UTC, java, final, score:  100
// you can also use imports, for example:
// import java.util.*; // you can write to stdout for debugging purposes, e.g.
// System.out.println("this is a debug message"); class Solution {
public int solution(int[] A) {
// write your code in Java SE 8
int zeroCnt=0, oneCnt =0;
for(int i=0; i<A.length; i++) {
if(A[i] == 0) {
zeroCnt += 1;
} else if(A[i] == 1) {
oneCnt += zeroCnt;
}
if(oneCnt > 1000000000)
return -1;
}
return oneCnt;
}
}
https://codility.com/demo/results/training8U5YGT-RJR/

最新文章

  1. Swift语言学习
  2. java异常
  3. 【转】Sublime Text3注册码(可用)
  4. 什么是HTML、XML和XHTML
  5. dictEntry **table;
  6. C# OR/Mapping 数据处理模式学习
  7. 使用 POJO 对象绑定请求参数
  8. echarts_部分图表配置_dataZoom精确控制显示数据数量
  9. 一行代码搭建 Python 静态服务器
  10. 业务侧有大量timeout请求超时日志
  11. react的dva框架初试
  12. dell t130服务器安装windowsserver2008R2系统
  13. 使用AWR报告诊断Oracle性能问题
  14. CentOS6.5 安装Python 的依赖包
  15. 8 -- 深入使用Spring -- 4...2 使用AspectJ实现AOP
  16. VS NuGet加载本地程序包
  17. 一段简单的代码记录如何通过 js 给 HTML 设置自定义属性,并且通过点击事件获取到所设置的自定义属性值
  18. Java8 新特性Stream 的学习和使用方法
  19. jupyter notebook 小技巧
  20. mongo 内存限制wiredTigerCacheSizeGB = 10

热门文章

  1. unix shell(壳)的简单实现
  2. ANT下载与安装--windows
  3. 【26.87%】【codeforces 712D】Memory and Scores
  4. Java设计模式透析之 —— 组合(Composite)
  5. 细数 Windows Phone 灭亡的七宗罪(过程很详细,评论很精彩,但主要还是因为太慢了,生态跟不上,太贪了,厂商不愿意推广)
  6. 机器学习: Python with Recurrent Neural Network
  7. 百度地图API二:根据标注点坐标范围计算显示缩放级别zoom自适应显示地图
  8. 【剑指offer】直扑克
  9. BS学习概述
  10. zcelib - One cplusplus C++ crossplatform library use for develop server,similar to ACE.