题目描述
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.
解释
给一个由0和1组成的数组,然后我们需要求出长度最大的子串,满足子串中0和1的个数相等。
思路 哈希表
首先我们可以有一个变量去记录在每一个位置0和1的差值。记录的方法是遇到1就加1,否则减1。那么这个变量(记为SUM)的值就代表在某一个位置1比0多了多少个。
这个变量有什么用呢?我们想一下,如果在数组的某两个位置SUM的值相同了,则说明在这两个位置中间的子串,0和1的个数一定是相同的。我们只需要求出这样的所有子串的最大长度即可。
因此我们还需要一个字典,字典的key就是SUM。如果SUM在字典中没有出现过,则把当前索引(即这个SUM的值第一次出现的位置)放入字典。否则我们计算当前索引和字典对应key的value的差(即为子串长度)。最后返回出最大长度即可。
注意在计算子串长度的时候不要更新字典,因为我们永远记录的是SUM某一个值第一次出现的位置,这样求出来的才是最大的长度。
代码
class Solution(object):
def findMaxLength(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
SUM = 0
d = {}
d[0] = -1
ans = 0
for i in range(len(nums)):
if nums[i] == 1:
SUM += 1
else:
SUM -= 1
if SUM in d:
ans = max(ans, i - d[SUM])
else:
d[SUM] = i
return ans