【leetcode485】最大连续1的个数 java题解

【leetcode分类下所有的题解均为作者本人经过权衡后挑选出的题解,在易读和可维护性上有优势 每题只有一个答案,避免掉了太繁琐的以及不实用的方案,所以不一定是最优解】

给定一个二进制数组, 计算其中最大连续1的个数。

示例 1:

输入: [1,1,0,1,1,1]
输出: 3
解释: 开头的两位和最后的三位都是连续1,所以最大连续1的个数是 3.
注意:

  • 输入的数组只包含 0 和1。
  • 输入数组的长度是正整数,且不超过 10,000。
class Solution {
    public int findMaxConsecutiveOnes(int[] nums) {
        int count = 0, max = Integer.MIN_VALUE;
        for(int num : nums){
            count = num == 0 ? 0 : count + 1;
            max = Math.max(max, count);
        }
        return max;
    }
}

思路:

  • count计数器遇到0则变成0,不等于0,则自增1
  • 每次迭代需比较出新与旧的count的最大值

猜你喜欢

转载自blog.csdn.net/weixin_43046082/article/details/88994478