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 提示:…
1
题型
8
代码语言
3
相关题
当前训练重点
简单 · 数组·driven
答案摘要
我们可以遍历数组,用一个变量 记录当前连续的 1 的个数,用另一个变量 记录最大连续 1 的个数。 当遍历到一个 1 时,将 加一,然后更新 的值为 和 本身的最大值,即 $\textit{ans} = \max(\textit{ans}, \textit{cnt})$。否则,将 重置为 0。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·driven 题型思路
题目描述
给定一个二进制数组 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 <= 105nums[i]不是0就是1.
解题思路
方法一:一次遍历
我们可以遍历数组,用一个变量 记录当前连续的 1 的个数,用另一个变量 记录最大连续 1 的个数。
当遍历到一个 1 时,将 加一,然后更新 的值为 和 本身的最大值,即 。否则,将 重置为 0。
遍历结束后,返回 的值即可。
时间复杂度 ,其中 为数组的长度。空间复杂度 。
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
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- 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.
常见陷阱
外企场景- 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.
进阶变体
外企场景- 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.