图解leetcode485.最大连续1的个数

图解leetcode485.最大连续1的个数,第1张

图解leetcode485.最大连续1的个数

1.题目描述:

给定一个二进制数组, 计算其中最大连续 1 的个数。示例给定:[1,1,0,0,1,1,1],输出结果为3。

2.自己写的代码:

class Solution {
    public int findMaxConsecutiveOnes(int[] nums) {

        int max = 0;
        for(int i = 0;i < nums.length;i++){
        int count = 0;
                while(i < nums.length && nums[i] == 1 ){
                    count++;
                    i++;
                }
                if(count > max){
                        max = count;
                    }
        }
        return max;
    }
}

优化代码:

class Solution {
    public int findMaxConsecutiveOnes(int[] nums) {
        int max = 0;
        int count = 0;
        for(int i = 0;i < nums.length;i++){
                if(nums[i] == 1){
                    count++;
                }else{
                    count = 0;
                }
                if(count > max){//每次都比较大小
                        max = count;
                    }
        }
        return max;
    }
}

最优解(以上均与官方解思路一致):

public int findMaxConsecutiveOnes(int[] nums) {
    int max = 0, cur = 0;
    for (int x : nums) {
        cur = x == 0 ? 0 : cur + 1;
        max = Math.max(max, cur);
    }
    return max;
}

3.双指针方法/滑动窗口方法:

使用left,right指针分别指向连续1的最左端和最右端,一旦出现0元素则left指针右移动到先前连续1的right后一位,最终获取right-left的最大值。

图解如下:

代码如下:

class Solution {
    public int findMaxConsecutiveOnes(int[] nums) {  
        
        int left = 0,right = 0,count = 0;
        while(right < nums.length){
            if(nums[right] == 0){
                count = Math.max(count,right - left);
                left = right + 1;//下一段起始点
            }
            right++;//right指针用来遍历
        }
        count = Math.max(count,right - left);
        return count;
    }
}

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5658204.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存