Skip to content

Commit 83dbb2d

Browse files
committed
feat: 20260211 check in
1 parent 6cd5f29 commit 83dbb2d

10 files changed

Lines changed: 71 additions & 738 deletions

.cursor/commands/publish-xhs.md

Lines changed: 0 additions & 26 deletions
This file was deleted.

.cursor/commands/write-leetcode-solution.md

Lines changed: 0 additions & 20 deletions
This file was deleted.
Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
# [525. 连续数组](https://leetcode.cn/problems/contiguous-array/)
2+
3+
> **日期**:2025-02-11
4+
> **所用时间**:2min
5+
> **知识点**:前缀和、哈希表
6+
7+
## 1. 题目描述
8+
9+
给定一个二进制数组 `nums`,找出含有相同数量的 `0``1` 的最长连续子数组,并返回该子数组的长度。
10+
11+
**示例 1:**
12+
13+
```
14+
输入: nums = [0,1]
15+
输出: 2
16+
说明: [0, 1] 是具有相同数量 0 和 1 的最长连续子数组。
17+
```
18+
19+
**示例 2:**
20+
21+
```
22+
输入: nums = [0,1,0]
23+
输出: 2
24+
说明: [0, 1] 或 [1, 0] 是具有相同数量 0 和 1 的最长连续子数组。
25+
```
26+
27+
**提示:**
28+
29+
- `1 <= nums.length <= 10^5`
30+
- `nums[i]` 不是 `0` 就是 `1`
31+
32+
## 2. 实际使用的算法:前缀和 + 哈希表
33+
34+
`0` 视为 `-1`,则「相同数量的 0 和 1」等价于子数组和为 0。对数组做前缀和 `s[0]=0, s[i]=s[i-1]+(nums[i]==1?1:-1)`。若 `s[i]=s[j]`(i>j),则区间 `[j+1,i]` 的和为 0,长度为 `i-j`。用哈希表记录每个前缀和**第一次**出现的下标,从左到右枚举右端点,若当前前缀和已出现过则用「当前下标 - 第一次下标」更新答案。
35+
36+
- **时间复杂度**:$O(n)$
37+
- **空间复杂度**:$O(n)$
38+
39+
**Python3**
40+
41+
```python
42+
class Solution:
43+
def findMaxLength(self, nums: List[int]) -> int:
44+
nums = [1 if x else -1 for x in nums]
45+
s = list(accumulate(nums, initial=0))
46+
47+
pos = {}
48+
ans = 0
49+
for i, x in enumerate(s):
50+
if x in pos:
51+
ans = max(ans, i - pos[x])
52+
else:
53+
pos[x] = i
54+
return ans
55+
```
56+
57+
优化:
58+
59+
```python
60+
class Solution:
61+
def findMaxLength(self, nums: List[int]) -> int:
62+
pos = {0: -1}
63+
ans = s = 0
64+
for i, x in enumerate(nums):
65+
s += 1 if nums[i] else -1
66+
if s in pos:
67+
ans = max(ans, i - pos[s])
68+
else:
69+
pos[s] = i
70+
return ans
71+
```
Binary file not shown.
Binary file not shown.
-299 KB
Binary file not shown.
-293 KB
Binary file not shown.

0 commit comments

Comments
 (0)