欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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