Codility----PassingCars
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.
// 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/
最新文章
- Swift语言学习
- java异常
- 【转】Sublime Text3注册码(可用)
- 什么是HTML、XML和XHTML
- dictEntry **table;
- C# OR/Mapping 数据处理模式学习
- 使用 POJO 对象绑定请求参数
- echarts_部分图表配置_dataZoom精确控制显示数据数量
- 一行代码搭建 Python 静态服务器
- 业务侧有大量timeout请求超时日志
- react的dva框架初试
- dell t130服务器安装windowsserver2008R2系统
- 使用AWR报告诊断Oracle性能问题
- CentOS6.5 安装Python 的依赖包
- 8 -- 深入使用Spring -- 4...2 使用AspectJ实现AOP
- VS NuGet加载本地程序包
- 一段简单的代码记录如何通过 js 给 HTML 设置自定义属性,并且通过点击事件获取到所设置的自定义属性值
- Java8 新特性Stream 的学习和使用方法
- jupyter notebook 小技巧
- mongo 内存限制wiredTigerCacheSizeGB = 10
热门文章
- unix shell(壳)的简单实现
- ANT下载与安装--windows
- 【26.87%】【codeforces 712D】Memory and Scores
- Java设计模式透析之 —— 组合(Composite)
- 细数 Windows Phone 灭亡的七宗罪(过程很详细,评论很精彩,但主要还是因为太慢了,生态跟不上,太贪了,厂商不愿意推广)
- 机器学习: Python with Recurrent Neural Network
- 百度地图API二:根据标注点坐标范围计算显示缩放级别zoom自适应显示地图
- 【剑指offer】直扑克
- BS学习概述
- zcelib - One cplusplus C++ crossplatform library use for develop server,similar to ACE.