首页 > 其他 > 详细

485. 最大连续1的个数

时间:2020-08-15 13:21:26      阅读:53      评论:0      收藏:0      [点我收藏+]

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

示例 1:

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

// 计数
class Solution {
    public int findMaxConsecutiveOnes(int[] nums) {
        int max = 0;
        int count = 0;
        for(int num : nums) {
            if(num == 1) {
                count++;
            } else {
                max = count > max ? count : max;
                count = 0;
            }
        }
        if(count > max) {
            max = count;
        }
        
        return max;
    }
}

// 双指针,起始点和结束点
class Solution {
    public int findMaxConsecutiveOnes(int[] nums) {
        int max = 0;
        int slow = 0, fast = 0;
        while(fast < nums.length) {
            if(nums[fast] == 1) {
                slow = fast;
                while(fast < nums.length && nums[fast] == 1) {
                    fast++;
                }
                max = Math.max(max, (fast - slow));
            }
            fast++;
        }
        return max;
    }
}

  

注意:

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/max-consecutive-ones
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

485. 最大连续1的个数

原文:https://www.cnblogs.com/PHUN19/p/13507671.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!