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
解题思路:
我的做法就是遍历一遍,当遇到0的时候与记录的最长1的个数进行比较,但是这种方法会在连续出现0的时候多次进行比较,不知道有没有什么好的解决方案。第一次提交的时候出错了,原因是当数组最后一个元素是1的时候,会跳出循环而不触发与记录的最大值的比较,因此修改为在返回的进行比较,选取二者中较大的值作为返回值。
1 class Solution { 2 public: 3 int findMaxConsecutiveOnes(vector<int>& nums) { 4 int maxNum = 0, num = 0; 5 for (int i = 0; i < nums.size(); i++) { 6 if (nums[i] == 0) { 7 if (num > maxNum) { 8 maxNum = num; 9 } 10 num = 0; 11 } 12 else { 13 num++; 14 } 15 } 16 return max(maxNum, num); 17 } 18 };