# 0525. 连续数组

### 题目地址(525. 连续数组)

<https://leetcode-cn.com/problems/contiguous-array/>

### 题目描述

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

 

示例 1:

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

示例 2:

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

 

提示：

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

### 前置知识

* 前缀和

### 公司

* 暂无

### 思路

**这道题的核心点在于将题目给的 0/1 数组转化为 -1/1 数组。**

这样问题转化为求数组中的一段连续区间，其和等于 0。求出数组任意一段区间的和，我们可以使用前缀和数组来加快这个过程，问题转化为**前缀和相同的两个最大区间长度**。由于是求最大，那么使用哈希表记录**第一次出现的位置**就变得显而易见了。

> 我在 《91 天学算法》的哈希篇中总结了这个套路。

### 关键点

* 将 0/1 数组转化为 -1/1 数组

### 代码

* 语言支持：Python3

Python3 Code:

```python
class Solution:
    def findMaxLength(self, A: List[int]) -> int:
        A = [1 if a == 0 else -1 for a in A]
        ans = acc = 0
        mapper = {0: -1}
        for i in range(len(A)):
            acc += A[i]
            if acc not in mapper:
                mapper[acc] = i
            else:
                ans = max(ans, i - mapper[acc])
        return ans
```

**复杂度分析**

令 n 为数组长度。

* 时间复杂度：$O(n)$
* 空间复杂度：$O(n)$

> 此题解由 [力扣刷题插件](https://leetcode-pp.github.io/leetcode-cheat/?tab=solution-template) 自动生成。

力扣的小伙伴可以[关注我](https://leetcode-cn.com/u/fe-lucifer/)，这样就会第一时间收到我的动态啦\~

以上就是本文的全部内容了。大家对此有何看法，欢迎给我留言，我有时间都会一一查看回答。更多算法套路可以访问我的 LeetCode 题解仓库：<https://github.com/azl397985856/leetcode> 。 目前已经 40K star 啦。大家也可以关注我的公众号《力扣加加》带你啃下算法这块硬骨头。

关注公众号力扣加加，努力用清晰直白的语言还原解题思路，并且有大量图解，手把手教你识别套路，高效刷题。

![](https://p.ipic.vip/s53udc.jpg)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://leetcode-solution-leetcode-pp.gitbook.io/leetcode-solution/medium/525.contiguous-array.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
