Given a binary array, find the maximum length of a contiguous subarray with equal number of 0 and 1.
Example 1:
Input: [0,1]
Output: 2
Explanation: [0, 1] is the longest contiguous subarray with equal number of 0 and 1.
Example 2:
Input: [0,1,0]
Output: 2
Explanation: [0, 1] (or [1, 0]) is a longest contiguous subarray with equal number of 0 and 1.
Note: The length of the given binary array will not exceed 50,000.
这道题想法比较难。首先当我们求subarray的时候,经常要使用的一个东西就是累积和。所以当没有思路的时候可以想想这个。这道题是用累计和做key,然后把该值的第一次出现的index作为val。为什么呢?
- 首先第一步先把所有的0都转换成-1,这样当和是0的时候就说明0和1数量相等。
- 当这个和没有出现的时候,就存到map里
- 当这个值出现的时候,就说明从第一次出现的那个index之后到现在这个index之间的和为0,那么就说明这个subarray符合要求。可以求其长度然后看看是不是最大
4.注意有一种特殊情况,就是累加和为0,那么说明从第一位到现在整个值就符合。
举个例子[1, 1, 1, 0, 0, 1 ]
首先转换为 [1, 1, 1, -1, -1, 1]
i | sum | hash | ans |
---|---|---|---|
0 | 1 | {1:0} | 0 |
1 | 2 | {1:0,2:1} | 0 |
2 | 3 | {1:0,2:1,3:1} | 0 |
3 | 2 | {1:0,2:1,3:1} | 2 (3-1) |
4 | 1 | {1:0,2:1,3:1} | 4 (4-0) |
5 | 2 | {1:0,2:1,3:1} | 4 (5-1) |
class Solution:
def findMaxLength(self, nums: List[int]) -> int:
if not nums: return 0
d = dict()
total, ans = 0, 0
for i in range(len(nums)):
total += 1 if nums[i] == 1 else -1
if total == 0:
ans = max(ans, i+1)
elif total in d:
ans = max(ans, i - d[total])
else:
d[total] = i
return ans