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 class Solution { 2 public: 3 int findMaxConsecutiveOnes(vector<int>& nums) { 4 int max = 0; 5 int temp = 0; 6 for(int i = 0; i < nums.size(); i ++) 7 { 8 if(nums[i]) 9 temp ++; 10 else 11 { 12 if (temp > max) 13 { 14 max = temp; 15 } 16 temp = 0; 17 } 18 } 19 if (temp > max) //最后一部分连续的判定 20 { 21 max = temp; 22 temp = 0; 23 } 24 return max; 25 } 26 };