525. Contiguous Array

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

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.

 

Note: The length of the given binary array will not exceed 50,000.

 

Approach #1: C++.

class Solution {
public:
    int findMaxLength(vector<int>& nums) {
        int ans = 0;
        int size = nums.size();
        unordered_map<int, int> prefix_sum;     // store the first position where the sum first appeared.
        int sum = 0;
        for (int i = 0; i < size; ++i) {
            sum += nums[i] ? 1 : -1;
            if (sum == 0) ans = i+1;
            else if (!prefix_sum.count(sum)) prefix_sum[sum] = i;
            else ans = max(ans, i - prefix_sum[sum]);
        }

        return ans;
    }
};

  

Approach #2: Java.

class Solution {
    public int findMaxLength(int[] nums) {
        for (int i = 0; i < nums.length; ++i) {
            if (nums[i] == 0) nums[i] = -1;
        }
        
        Map<Integer, Integer> sumToIndex = new HashMap<>();
        sumToIndex.put(0, -1);
        int sum = 0, max = 0;
        
        for (int i = 0; i < nums.length; ++i) {
            sum += nums[i];
            if (sumToIndex.containsKey(sum)) {
                max = Math.max(max, i - sumToIndex.get(sum));
            } else {
                sumToIndex.put(sum, i);
            }
        }
        return max;
    }
}

  

Approach #3: Python.

class Solution(object):
    def findMaxLength(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        count = 0
        max_length = 0
        table = {0 : 0}
        for index, num in enumerate(nums, 1):
            if num == 0:
                count -= 1
            else:
                count += 1
            
            if count in table:
                max_length = max(max_length, index - table[count])
            else:
                table[count] = index
                
        return max_length
            

  

Analysis:

In this problem if we use double cycle traversing the vector to find the subarray, because the length of the given binary array will not exceed 50,000, it will Time Limt Exceeded.

So we can use a hash table to save time using space.

First, we have to make the elements in the nums which equal to 0 transform to -1.

Then we travel the array and calculate the prefix sum. if the sum don't count in hash map, we put sum into the hash table, else i - prefix_sum[sum] is a dummy answer which we want to find.

Having one thing we have to notice is which if the array is [0, 1], you may finding that the prefix sum never appeared in this case, so it will return 0 finally. but the really answer is 2. How can we solve this problem?

  • In approach one we using a if statemen to judge if the answer equal to 0 we coulde make ans = i + 1 using this way we can solve the problem of initialization.
  • In approach two we push the key and value {0, -1} in the first, this have the same effect with the first one.

  

 

 

posted @ 2018-11-19 10:41  Veritas_des_Liberty  阅读(209)  评论(0编辑  收藏  举报