https://leetcode.com/problems/contiguous-array/#/description
01序列数组,找出0和1个数相同的最长子数组长度
将0置为-1,找和为0的sum(i, j)。用HashMap保存第一个和为sum的位置map.put(sum, i)。问题变形为求前缀和为0的最长子数组。
public class Solution {
public int findMaxLength(int[] nums) {
for (int i = 0; i < nums.length; i++) {
if (nums[i] == 0) {
nums[i] = -1;
}
}
int max = 0;
int sum = 0;
HashMap<Integer, Integer> map = new HashMap();
map.put(0, -1);
for (int i = 0; i < nums.length; i++) {
sum += nums[i];
if (map.containsKey(sum)) {
max = Math.max(max, i - map.get(sum));
} else {
map.put(sum, i);
}
}
return max;
}
}