[leetCode]485. 最大连续1的个数

题目

https://leetcode-cn.com/problems/max-consecutive-ones/

[leetCode]485. 最大连续1的个数

滑动窗口

class Solution {
    public int findMaxConsecutiveOnes(int[] nums) {
        int len = nums.length;
        int left = 0;
        int right = 0;
        int maxOneCnt = 0;
        while (right < len) {
            int num = nums[right++];
            if (num == 1) {
                maxOneCnt = Math.max(right - left, maxOneCnt);
            } else {
                left = right;
            }
        }
        return maxOneCnt;
    }
}

一次遍历

class Solution {
    public int findMaxConsecutiveOnes(int[] nums) {
        int len = nums.length;
        int count = 0;
        int maxCount = 0;
        for (int i = 0; i < len; i++) {
            if (nums[i] == 1) {
                count++;
            } else {
                maxCount = Math.max(maxCount, count);
                count = 0;
            }
        } 
        maxCount = Math.max(maxCount, count);
        return maxCount;
    }
}
上一篇:力扣485. 最大连续1的个数-C语言实现-简单题


下一篇:485. 最大连续1的个数(数组)