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:
0
and 1
.考虑时间复杂度,用一次循环完成。设置计数器,当出现1的时候加加,当出现0的时候计数中断,从零开始重新计数,并将之前得到的连续1的个数进行保存。每次只保存连续1的最大个数,放在countermax里面。最后要对边界情况进行特殊处理,具体代码如下:
class Solution { public: int findMaxConsecutiveOnes(vector<int>&nums) { int size = nums.size(); int counter = 0;//计数器 int counterMax = 0;//保留最大结果 int record = 1;//把1标记一下 for (int i = 0; i < size; i++) { //一次遍历数组 if (record == nums[i]) { //满足条件开始统计 counter++; if (i == size - 1) return counterMax>counter?counterMax:counter; //末尾情况做特殊处理 } else { if (counter > counterMax) { counterMax = counter;//保留最大连续个数 } counter = 0; } } return counterMax; } };
【LeetCode】14.Array and String — Max Consecutive Ones 一的最大连续次数
原文:https://www.cnblogs.com/hu-19941213/p/11002525.html