Given a binary array, find the maximum length of a contiguous subarray with equal number of 0 and 1.
Input: [0,1]
Output: 2
Explanation: [0, 1] is the longest contiguous subarray with equal number of 0 and 1.
Input: [0,1,0]
Output: 2
Explanation: [0, 1] (or [1, 0]) is a longest contiguous subarray with equal number of 0 and 1.
例子: array : [0, 1, 0, 1, 1]
1 cnt : 0 1 1 2 2
0 cnt : 1 1 2 2 2
diff :0 -1 0 -1 0 0
loc :-1 0 1 2 3 4
public int findMaxLength(int[] nums) {
if (nums == null || nums.length == 0) {
return 0;
}
int max = 0;
int zeroCnt = 0;
int oneCnt = 0;
// <diff, loc>
HashMap<Integer, Integer> hm = new HashMap<>();
hm.put(0, -1);
for (int i = 0; i < nums.length; i++) {
int cur = nums[i];
if (cur == 1) {
oneCnt++;
} else {
zeroCnt++;
}
int diff = oneCnt - zeroCnt;
if (hm.containsKey(diff)) {
int size = i - hm.get(diff);
max = Math.max(max, size);
} else {
hm.put(diff, i);
}
}
return max;
}
public class Solution {
public int findMaxLength(int[] nums) {
Map<Integer, Integer> map = new HashMap<>();
map.put(0, -1);
int maxlen = 0, count = 0;
for (int i = 0; i < nums.length; i++) {
count = count + (nums[i] == 1 ? 1 : -1);
if (map.containsKey(count)) {
maxlen = Math.max(maxlen, i - map.get(count));
} else {
map.put(count, i);
}
}
return maxlen;
}
}