
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
--------------------------------------------------------------------------------------------------------------------------------------
这个题可以用双指针,时间复杂度是O(n),空间复杂度是O(1)。建立一个快指针和慢指针。
C++代码1:
class Solution {
public:
int findMaxConsecutiveOnes(vector<int>& nums) {
if(nums.size() == )
return ;
int maxSum = ;
int sum = ;
for(int i = ; i < nums.size(); i++){
if(nums[i] == ){
sum++;
}
else{
maxSum = max(sum,maxSum);
sum = ;
}
}
//这个不能漏掉
if(sum > maxSum)
maxSum = sum;
return maxSum;
}
};
C++代码2:
class Solution {
public:
int findMaxConsecutiveOnes(vector<int>& nums) {
if(nums.size() == )
return ;
int maxSum = ;
int sum = ;
for(int i = ; i < nums.size(); i++){
if(nums[i] == ){
sum++;
}
else{
sum = ;
}
maxSum = max(sum,maxSum);
}
return maxSum;
}
};