Lintcode 994. Contiguous Array (Medium) (Python)

Contiguous Array

Description:

Given a binary array, find the maximum length of a contiguous subarray with equal number of 0 and 1.

Example
Example 1:

Input: [0,1]
Output: 2
Explanation: [0, 1] is the longest contiguous subarray with equal number of 0 and 1.
Example 2:

Input: [0,1,0]
Output: 2
Explanation: [0, 1] (or [1, 0]) is a longest contiguous subarray with equal number of 0 and 1.
Notice
The length of the given binary array will not exceed 50,000.

Code:

class Solution:
    """
    @param nums: a binary array
    @return: the maximum length of a contiguous subarray
    """
    def findMaxLength(self, nums):
        # Write your code here
        dic = {0:-1}
        sum = 0
        maxLen = 0
        for i in range(len(nums)):
            if nums[i]==1:
                sum += 1
            else:
                sum -= 1
            if sum not in dic:
                dic[sum] = i
            elif sum in dic:
                maxLen = max(maxLen, i-dic[sum])
        return maxLen

猜你喜欢

转载自blog.csdn.net/weixin_41677877/article/details/82382064
今日推荐