LeetCode 525: Contiguous Array

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, 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

你可能感兴趣的:(算法,python,LeetCode)