思路:将所有的0都转化为-1,然后求前缀和为0的部分即可。
需要一个map,维护前缀和,每次到了新的结点,就去找和之前的前缀和相等的结点,然后坐标相减得出结果。
class Solution {
public int findMaxLength(int[] nums) {
//变种前缀和,
int max = 0;
int res = 0;
HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
map.put(0,-1);
//前缀和放最远部分的
for(int i=0;i<nums.length;i++){
if(nums[i]==0) nums[i]=-1;//改为-1
res = res + nums[i];//计算当前前缀和
//在map中寻找和为0的部分,然后当前位置-最远位置,之后与max比较。
//如果没找到,就标记为无限负。
if(map.containsKey(res)){
max = Math.max(max,i-map.get(res));
} else {
map.put(res,i);
}
}
return max;
}
}