LeetCode 题解工作台

连续数组

给定一个二进制数组 nums , 找到含有相同数量的 0 和 1 的最长连续子数组,并返回该子数组的长度。 示例 1: 输入: nums = [0,1] 输出: 2 说明: [0, 1] 是具有相同数量 0 和 1 的最长连续子数组。 示例 2: 输入: nums = [0,1,0] 输出: 2 说…

category

3

题型

code_blocks

6

代码语言

hub

3

相关题

当前训练重点

中等 · 数组·哈希·扫描

bolt

答案摘要

根据题目描述,我们可以将数组中的 视作 ,这样当遇到 时,前缀和 就会减一,当遇到 时,前缀和 就会加一。因此,假设前缀和 在下标 和 处的值相等,其中 $j < i$,那么从下标 $j + 1$ 到 的子数组中 和 的数量就是相等的。 我们使用哈希表存储所有的前缀和以及它们第一次出现的下标,初始时,我们将 的前缀和映射到 。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数组·哈希·扫描 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给定一个二进制数组 nums , 找到含有相同数量的 01 的最长连续子数组,并返回该子数组的长度。

 

示例 1:

输入:nums = [0,1]
输出:2
说明:[0, 1] 是具有相同数量 0 和 1 的最长连续子数组。

示例 2:

输入:nums = [0,1,0]
输出:2
说明:[0, 1] (或 [1, 0]) 是具有相同数量 0 和 1 的最长连续子数组。

示例 3:

输入:nums = [0,1,1,1,1,1,0,0,0]
输出:6
解释:[1,1,1,0,0,0] 是具有相同数量 0 和 1 的最长连续子数组。

 

提示:

  • 1 <= nums.length <= 105
  • nums[i] 不是 0 就是 1
lightbulb

解题思路

方法一:前缀和 + 哈希表

根据题目描述,我们可以将数组中的 00 视作 1-1,这样当遇到 00 时,前缀和 ss 就会减一,当遇到 11 时,前缀和 ss 就会加一。因此,假设前缀和 ss 在下标 jjii 处的值相等,其中 j<ij < i,那么从下标 j+1j + 1ii 的子数组中 0011 的数量就是相等的。

我们使用哈希表存储所有的前缀和以及它们第一次出现的下标,初始时,我们将 00 的前缀和映射到 1-1

遍历数组,计算前缀和 ss,如果 ss 已经在哈希表中,那么我们就找到了一个和为 00 的子数组,其长度为 id[s]i - d[s],其中 d[s]d[s] 是哈希表中保存的 ss 第一次出现的下标。如果 ss 不在哈希表中,我们将 ss 与它的下标 ii 存入哈希表。

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

1
2
3
4
5
6
7
8
9
10
11
12
class Solution:
    def findMaxLength(self, nums: List[int]) -> int:
        d = {0: -1}
        ans = s = 0
        for i, x in enumerate(nums):
            s += 1 if x else -1
            if s in d:
                ans = max(ans, i - d[s])
            else:
                d[s] = i
        return ans
speed

复杂度分析

指标
时间complexity is O(n) because each element is scanned once and hash map operations are O(1) on average. Space complexity is O(n) to store prefix sums in the hash map, which is necessary for efficient lookups.
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    You may notice that a naive double loop approach times out for large arrays.

  • question_mark

    Converting 0s to -1s is a common hint that this is a prefix sum pattern.

  • question_mark

    Hash map usage suggests tracking first occurrences to maximize subarray length.

warning

常见陷阱

外企场景
  • error

    Forgetting to convert 0s to -1s, which breaks the sum-to-zero pattern.

  • error

    Overwriting the first occurrence of a prefix sum in the hash map, which can underestimate the maximum length.

  • error

    Trying to return the subarray itself instead of just its length, adding unnecessary complexity.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Count the number of contiguous subarrays with equal 0s and 1s instead of maximum length.

  • arrow_right_alt

    Handle arrays with more than two binary values, e.g., 0,1,2, requiring multiple prefix sums.

  • arrow_right_alt

    Find maximum length subarray with equal numbers of two specific elements in a non-binary array.

help

常见问题

外企场景

连续数组题解:数组·哈希·扫描 | LeetCode #525 中等