Given a binary array, find the maximum length of a contiguous subarray with equal number of 0 and 1.
Example 1:
1Input: [0,1] 2Output: 2 3Explanation: [0, 1] is the longest contiguous subarray with equal number of 0 and 1.
Example 2:
1Input: [0,1,0] 2Output: 2 3Explanation: [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.
1public class Solution { 2 public int findMaxLength(int[] nums) { 3 if(nums == null || nums.length == 0){ 4 return 0; 5 } 6 for(int i=0; i<nums.length; i++){ 7 if(nums[i] == 0){ 8 nums[i] = -1; //先把所有的0变成-1,这样就是求sum为0的最大区间 9 } 10 } 11 int sum = 0, max = 0; 12 HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); 13 map.put(0, -1); 14 for(int i=0; i<nums.length; i++){ 15 sum += nums[i]; 16 if(!map.containsKey(sum)){ 17 map.put(sum, i); 18 }else{ 19 max = Math.max(max, i-map.get(sum)); 20 } 21 } 22 return max; 23 } 24}