首页 > 其他 > 详细

【LeetCode】14.Array and String — Max Consecutive Ones 一的最大连续次数

时间:2019-06-11 13:57:12      阅读:102      评论:0      收藏:0      [点我收藏+]

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 and 1.
  • The length of input array is a positive integer and will not exceed 10,000

考虑时间复杂度,用一次循环完成。设置计数器,当出现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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!