485. Max Consecutive Ones
Given a binary array, find the maximum number of consecutive 1s in
this array.Example 1: Input: [1,1,0,1,1,1] Output: 3 Explanation: The first two
digits or the last three digits are consecutive 1s.The maximum number of consecutive 1s is 3. Note:
The input array will only contain 0 and 1. The length of input array
is a positive integer and will not exceed 10,000
思路
遍历+计数, 遍历一遍数组, 当1时候计数器计数, 不是1时候归零
复杂度
时间O(n) 空间O(1)
代码
class Solution {
public int findMaxConsecutiveOnes(int[] nums) {
int res = 0, count = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] == 1) {
count++;
res = Math.max(count, res);
}
else {
count = 0;
}
}
return res;
}
}
阅读 1.2k
26 声望
10 粉丝
0 条评论
得票最新