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.
解题思路:本人第一思路是利用暴力搜索两层for循环,但是这种方法估计过于简单和复杂度较高,然后看了题解自己理解了一种方法,利用map来写,复杂度O(n)。
public int findMaxLength(int[] nums) {
int res = 0,num = 0;
for(int i = 0;i<nums.length;i++){
if (nums[i] == 0)
nums[i] = -1;
}
Map<Integer,Integer> map = new HashMap<>();
for(int i = 0;i<nums.length;i++){
num +=nums[i];
if (num == 0)
res = i+1;//绝对位置
if (map.containsKey(num))
res = Math.max(i-map.get(num),res);//i到i是一个相对位置,间隔空隙不变
else
map.put(num,res);
}
return res;
}
}