题目描述

输入只有0和1的数组(长度为正整数,且<10000),找到最大的连续1的个数
比如[1,1,0,1,1,1],输出3

思路

遍历数组,统计当前连续个数curCount和最大连续值maxCount。If当前数组值为1,则curCount++;否则(值为0)比较curCount和maxCount,看是否需要替换,并把curCount置0
最后返回maxCount

错误:对于[1]这种边界条件没有考虑完全。这种时候上面的逻辑会输出0,而应该是1。也就是结束的时候需要增加一个比较,万一如果最后的连续1的个数比较多。

——解决:在遍历完,返回之前,增加一个[比较curCount和maxCount,看是否需要替换]。

代码

public class Solution {
    public int findMaxConsecutiveOnes(int[] nums) {
        int curCount=0,maxCount=0;
        
        for(int n: nums){
            if(n==1)
                curCount++;
            else{
                if(curCount>maxCount)
                    maxCount=curCount;
                curCount=0;
            }
        }
        if(curCount>maxCount)
                    maxCount=curCount;
        return maxCount;
    }
}

相关文章:

  • 2022-12-23
  • 2021-11-14
  • 2021-09-11
  • 2021-07-31
  • 2022-12-23
  • 2022-12-23
  • 2021-10-12
猜你喜欢
  • 2021-11-24
  • 2022-12-23
  • 2021-08-24
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案