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;
}
在tutorial里发现了一个优雅点的写法:
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;
}
}