题目描述:
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
and1
. - The length of input array is a positive integer and will not exceed 10,000
代码如下:
class Solution {
public:
int findMaxConsecutiveOnes(vector<int>& nums) {
int maxn=0; //最大连续次数
int counter=0; //当前1连续了多少次
for(int i=0;i<nums.size();i++){
if(nums[i]){
counter++;
if(counter>maxn){
maxn=counter;
}
}
else{
counter=0;
}
}
return maxn;
}
};
耗时39ms,击败了46.26%的c++程序。
需要注意的是maxn的初值要设为0,第一次写没多想直接设为了-1,结果还WA了一次,因为当数组只包含一个0时,我返回-1。