LeetCode 485. 最大连续 1 的个数

485. 最大连续 1 的个数

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

示例 1:

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

示例 2:

输入:nums = [1,0,1,1,0,1]
输出:2

提示:

  • 1 <= nums.length <= 10^5
  • nums[i] 不是 0 就是 1.

提示 1

You need to think about two things as far as any window is concerned. One is the starting point for the window. How do you detect that a new window of 1s has started? The next part is detecting the ending point for this window. How do you detect the ending point for an existing window? If you figure these two things out, you will be able to detect the windows of consecutive ones. All that remains afterward is to find the longest such window and return the size.

解法1:一次遍历


Java版:

class Solution {
    public int findMaxConsecutiveOnes(int[] nums) {
        int ans = 0;
        int count = 0;
        int n = nums.length;
        for (int i = 0; i < n; i++) {
            if (nums[i] == 0) {
                ans = Math.max(ans, count);
                count = 0;
            } else if (nums[i] == 1) {
                count++;
                ans = Math.max(ans, count);
            }
        }
        return ans;
    }
}

复杂度分析

  • 时间复杂度:O(n),其中 n 是数组的长度。需要遍历数组一次。

  • 空间复杂度:O(1)。

Python3版:

class Solution:
    def findMaxConsecutiveOnes(self, nums: List[int]) -> int:
        ans = 0
        count = 0
        for i in range(len(nums)):
            if nums[i] == 0:
                ans = max(ans, count)
                count = 0
            else:
                count = count + 1
                ans = max(ans, count)
        return ans

复杂度分析

  • 时间复杂度:O(n),其中 n 是数组的长度。需要遍历数组一次。

  • 空间复杂度:O(1)。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值