题目: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.
这个题目好像是新出的,其实我一看到这个题的时候思路有点乱,一直没有理清楚0和1应该怎么去处理他们的关系才能保证得到正确的答案。然后去看了一下discuss,下面记录一下。
方法一,使用一个数组diff[]来记录当前位置之前所有出现的1减去所有的0。然后使用map来保存diff[i]与其索引i。这样的话每当diff[j] == diff[i]时,就意味着i到j之间是一个满足条件的子数组。这种方法击败了65%的用户。代码入下:
public int findMaxLength(int[] nums) {
int res = 0;
Map<Integer, Integer> map = new HashMap<>();
int n = nums.length;
int [] diff = new int[n+1];
map.put(0, 0);
for(int i=1; i<=n; i++){
diff[i] = diff[i-1] + (nums[i-1] == 0 ? -1 : 1);
if(!map.containsKey(diff[i]))
map.put(diff[i], i);
else
res = Math.max(res, i-map.get(diff[i]));
}
return res;
}
方法二,思路类似,也是使用map来记录之前遍历过的数组信息,这种方法击败了95.7%的用户。代码入下:
public int findMaxLength2(int[] nums) {
Map<Integer, Integer> map = new HashMap<Integer, Integer>() {{put(0,0);}};
int maxLength = 0, runningSum = 0;
for (int i=0;i<nums.length;i++) {
runningSum += nums[i];
Integer prev = map.get(2*runningSum-i-1);
if (prev != null) maxLength = Math.max(maxLength, i+1-prev);
else map.put(2*runningSum-i-1, i+1);
}
return maxLength;
}