Given a binary array
nums
, return the maximum length of a contiguous subarray with an equal number of0
and1
.
class Solution:
def findMaxLength(self, nums):
# 记录目前为止的 pattern
temp = 0
res = 0
mp = {0:-1}
for i, num in enumerate(nums):
if num == 0:
temp -= 1
else:
temp += 1
# 记录新 pattern 和对应的 index 值
if temp not in mp:
mp[temp] = i
# 同 value 表示中间的 0 和 1 个数相等,更新 length
else:
res = max(res, i - mp[temp])
return res