LeetCode 525: Contiguous Array
程序员文章站
2022-07-15 14:31:34
...
Given a binary array, find the maximum length of a contiguous subarray with equal number of 0 and 1.
Using hashmap to solve it. Map<sum, index>, the hashmap only stores the sum of first (index + 1) numbers which occurs at the first time. 0 is regarded as -1 while suming over the array. When a sum exists in the hashmap, calculating the difference of the current index and the hashmap index. compare the maxlength and the difference, If the difference is bigger, replacing the maxlength with the difference.
class Solution:
def findMaxLength(self, nums: 'List[int]') -> 'int':
# Iteration
if not nums or len(nums) == 0:
return 0
dic = {0:-1}
# start, end = 0, 0
sum_, max_l = 0, 0
for i in range(len(nums)):
sum_ += -1 if nums[i] == 0 else 1
if sum_ not in dic:
dic[sum_] = i
else:
max_l = max(max_l, i-dic[sum_])
# start = dic[sum_] + 1
# end = i
# print(start, end)
return max_l
推荐阅读
-
【LeetCode】Two Sum & Two Sum II - Input array is sorted & Two Sum IV - Input is a BST
-
【一天一道LeetCode】#26. Remove Duplicates from Sorted Array
-
LeetCode 33. Search in Rotated Sorted Array && 81. Search in Rotated Sorted Array II
-
Leetcode 33 Search in Rotated Sorted Array
-
LeetCode·33. Search in Rotated Sorted Array
-
leetcode 33. Search in Rotated Sorted Array
-
LeetCode------Search in Rotated Sorted Array
-
LeetCode Search in Rotated Sorted Array
-
Leetcode525-Contiguous Array
-
LeetCode 525. Contiguous Array