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
Example 2:
Input: [0, 1, 0] Output: 2
Note: The length of the given binary array will not exceed 50,000.
题目的意思翻译过来讲就是给定一个0/1串,找到一个长度最大的子串使得字串中0和1的数目相等。这题因为最大输入0/1串的长度可以达到5万,所以最简单的求出所有符合题意的子串的暴力解法显然不合适。于是转变思路,将数组中的0全部变为-1,这样就是找和为0的最大子串。假设前3个字符串的和为1,前7个字符串的和也为1,那么显然从下标为 3到6的字串和必定为0,这就是满足题意。用这种方法遍历一次数组我们就能找出最长的符合题意的子串,负责度降为了O(n)。
代码如下:
class Solution(object):
def findMaxLength(self, nums):
if len(nums) <=1:
return 0
for index in range(len(nums)):
if nums[index] == 0:
nums[index] = -1
sumMap ={0:-1}
tar = 0
sum_ = 0
# sumMap[0] = -1
for index in range(len(nums)):
sum_ += nums[index]
if sum_ in sumMap:
tar = max(tar, index - sumMap[sum_])
else:
sumMap[sum_] = index
return tar