版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/dpengwang/article/details/86213950
给定一个01数组,求最长的连续子数组的长度,使得这个子数组中0和1的个数相等:
暴力法会超时,所以先不考虑
方法1:
可以让所有0变成-1,这样满足条件的子数组的和为0。从左往右遍历数组,求数组最左边到每个index位置的和,并将结果保存在字典中。如果在index1和index2位置的和相同,那么说明index1~index2中间这一段的和为0。
AC代码
class Solution:
def findMaxLength(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
for i in range(len(nums)):
if nums[i] ==0:
nums[i]=-1
dictionary ={}
dictionary[0] = -1
res = 0
sum = 0
for i in range(len(nums)):
sum = sum + nums[i]
if sum in dictionary:
res = max(i-dictionary[sum],res)
else:
dictionary[sum] =i
return res
方法2:
其实跟方法1思想有些类似,我们用一个计数器count,遇到1就加一,遇到0就减一,那么如果两个位置的count值相等,那么说明两个位置中间的数组0和1相等
AC代码:
class Solution:
def findMaxLength(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
res = 0
count = 0
dictionary = {0:-1}
for i in range(len(nums)):
if nums[i] ==1:
count+=1
else:
count-=1
if count in dictionary:
res = max(res,i-dictionary[count])
else:
dictionary[count] = i
return res