图解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;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值