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.

思路:遇见0,-1,遇见1,+1,这样跟presum一样,如果cursum重复了,说明中间有相等的0,1,这样就是类似于two sum的解法,扫描一遍就可以了。注意,还没又开始的时候,要put(0,-1) ,  It means that, before we loop this array, the sum is 0 in initial, and because we haven't starting loop, so the index = -1. 也就是[0,1] 这种情况,如果没有 (0,-1),那么就计算出len = 2,也就是还没进行loop的时候,index = -1;这样好进行index的计算;

class Solution {
    public int findMaxLength(int[] nums) {
        if(nums == null || nums.length == 0) {
            return 0;
        }
        //      cursum,   index
        HashMap sumToIndex = new HashMap<>();
        sumToIndex.put(0, -1);
        int maxlen = 0;
        int cursum = 0;
        for(int i = 0; i < nums.length; i++) {
            cursum += nums[i] == 0 ? -1 : 1;
            if(sumToIndex.containsKey(cursum)) {
                maxlen = Math.max(maxlen, i - sumToIndex.get(cursum));
            } else {
                sumToIndex.put(cursum, i);
            }   
        }
        return maxlen;
    }
}

 

你可能感兴趣的:(hashmap)