题目
Given a binary array, find the maximum number of consecutive 1s in this array.
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,数组中值仅包含0和1
2,输入数组长度为正整数,且不会超过10000
思路
遍历数组,如果是1,则计数加一,如果是0,则将当前计数值和最大值比较更新。然后计数计数清零。
代码
class Solution {
public:
int findMaxConsecutiveOnes(vector<int>& nums) {
int len = nums.size();
int max = 0;
int cnt = 0;
for(int i = 0; i < len;i++){
if(nums[i] != 0){
cnt++;
}else{
if(cnt > max){
max = cnt;
}
cnt = 0;
}
}
if(cnt > max){
max = cnt;
}
return max;
}
};