美文网首页
【Leetcode题】485. 最大连续1的个数

【Leetcode题】485. 最大连续1的个数

作者: 一个有想法的人 | 来源:发表于2018-03-31 14:32 被阅读0次

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

示例 1:

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

注意:

输入的数组只包含 0 和1。
输入数组的长度是正整数,且不超过 10,000。

第一次提交的答案:

class Solution {
    public int findMaxConsecutiveOnes(int[] nums) {
        if(nums == null || nums.length == 0) {
            return 0;
        }
        int max = 0;
        int temp = 0;
        for(int i=0;i<nums.length;i++){
            if(nums[i] == 1){
                temp ++;
            }
            if(nums[i] == 0){
                //比较max 和 temp
                if(max < temp){
                    max = temp;
                }
                temp = 0;
            }
        }
        return max;
    }
}

题目比较简单,但还是出现边界未检测的问题。 上面的代码只适应于以0结尾的数组,如果是[1],[1,0,1,1]这样的数组结果就错了。解决这个问题只要在最后判断下temp和max即可。

正确的答案是: 【耗时: 10ms】

class Solution {
    public int findMaxConsecutiveOnes(int[] nums) {
        if(nums == null || nums.length == 0) {
            return 0;
        }
        int max = 0;
        int temp = 0;
        for(int i=0;i<nums.length;i++){
            if(nums[i] == 1){
                temp ++;
            }
            if(nums[i] == 0){
                //比较max 和 temp
                if(max < temp){
                    max = temp;
                }
                temp = 0;
            }
        }
        if(temp > max) {
            return temp;
        }
        return max;
    }
}

还有一种更简洁的写法:

class Solution {
    public int findMaxConsecutiveOnes(int[] nums) {
        if(nums == null || nums.length == 0) {
            return 0;
        }
        int max = 0;
        int temp = 0;
        for(int i=0;i<nums.length;i++){
            if(nums[i] == 1){
                temp ++;
                if(temp > max){
                    max = temp;
                }
            }
            else{
                temp = 0;
            }
        }
        return max;
    }
}

看看别人的思路:记住上次0出现的位置,然后下次出现0就可以计算连续1的个数,省去了temp++的过程。
且看实现:

class Solution {
    public int findMaxConsecutiveOnes(int[] nums) {
        if(nums == null || nums.length == 0) {
            return 0;
        }
        int index = -1;
        int max = 0;
        for(int i=0;i<nums.length;i++) {
            if(nums[i] == 0) { //遇到0了,要对比下
                int temp = i - 1 - index;
                max = Math.max(temp, max);
                index = i;
            }
        }
        max = Math.max(max, nums.length-1-index);
        return max;
    }
}

总结: 求连续区间数据不仅可以通过计数实现,还可以通过两端索引之差实现,且后者性能更好。

相关文章

网友评论

      本文标题:【Leetcode题】485. 最大连续1的个数

      本文链接:https://www.haomeiwen.com/subject/xrugcftx.html