LeetCode 题解工作台

最大连续 1 的个数

给定一个二进制数组 nums , 计算其中最大连续 1 的个数。 示例 1: 输入: nums = [1,1,0,1,1,1] 输出: 3 解释: 开头的两位和最后的三位都是连续 1 ,所以最大连续 1 的个数是 3. 示例 2: 输入: nums = [1,0,1,1,0,1] 输出: 2 提示:…

category

1

题型

code_blocks

8

代码语言

hub

3

相关题

当前训练重点

简单 · 数组·driven

bolt

答案摘要

我们可以遍历数组,用一个变量 记录当前连续的 1 的个数,用另一个变量 记录最大连续 1 的个数。 当遍历到一个 1 时,将 加一,然后更新 的值为 和 本身的最大值,即 $\textit{ans} = \max(\textit{ans}, \textit{cnt})$。否则,将 重置为 0。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数组·driven 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给定一个二进制数组 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 <= 105
  • nums[i] 不是 0 就是 1.
lightbulb

解题思路

方法一:一次遍历

我们可以遍历数组,用一个变量 cnt\textit{cnt} 记录当前连续的 1 的个数,用另一个变量 ans\textit{ans} 记录最大连续 1 的个数。

当遍历到一个 1 时,将 cnt\textit{cnt} 加一,然后更新 ans\textit{ans} 的值为 cnt\textit{cnt}ans\textit{ans} 本身的最大值,即 ans=max(ans,cnt)\textit{ans} = \max(\textit{ans}, \textit{cnt})。否则,将 cnt\textit{cnt} 重置为 0。

遍历结束后,返回 ans\textit{ans} 的值即可。

时间复杂度 O(n)O(n),其中 nn 为数组的长度。空间复杂度 O(1)O(1)

1
2
3
4
5
6
7
8
9
10
11
class Solution:
    def findMaxConsecutiveOnes(self, nums: List[int]) -> int:
        ans = cnt = 0
        for x in nums:
            if x:
                cnt += 1
                ans = max(ans, cnt)
            else:
                cnt = 0
        return ans
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Looking for O(n) time complexity using direct array traversal.

  • question_mark

    Expect awareness of edge cases such as all 1s or all 0s.

  • question_mark

    Interest in minimal extra space and clear variable tracking.

warning

常见陷阱

外企场景
  • error

    Forgetting to update the maximum after the last element if the array ends with 1s.

  • error

    Resetting the counter incorrectly or double-counting sequences.

  • error

    Using unnecessary additional arrays instead of simple integer counters.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Count maximum consecutive zeros instead of ones.

  • arrow_right_alt

    Allow flipping at most one 0 to 1 to find the maximum consecutive 1s.

  • arrow_right_alt

    Return the start and end indices of the longest consecutive 1s sequence.

help

常见问题

外企场景

最大连续 1 的个数题解:数组·driven | LeetCode #485 简单