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
解题思路:将数组每个数据判断,先判断第一个数据是否为1,每个数据与前一个比较判断(从第二个开始)。分为三种情况分别判断。
注意:只有为1的时候才能有效,为0的时候不算进去
class Solution { public: int findMaxConsecutiveOnes(vector<int>& nums) { int max=0; int count=0; if(nums[0]==1){ max=1; count=1; } for(int i=1;i<nums.size();i++){ if(nums[i]==1&&nums[i-1]==1){ count++; if(count>max){ max=count; } } else if(nums[i]==0){ count=0; } else if(nums[i]==1 &&nums[i-1]==0){ count=1; } } if(count>max)max=count; return max; } };