# One pass,use a HashMap to record 0-1 count difference

• ``````public class Solution {
public int findMaxLength(int[] nums) {
HashMap<Integer,Integer> map=new HashMap<>();
map.put(0,-1);

int zero=0;
int one=0;
int len=0;
for(int i=0;i<nums.length;i++){
if(nums[i]==0){
zero++;
}else{
one++;
}

if(map.containsKey(zero-one)){
len=Math.max(len,i-map.get(zero-one));
}else{
map.put(zero-one,i);
}
}

return len;
}
}``````

• Thanks. This was very helpful.

• nice solution without modifying current array content.

• @bxiao0801
Thanks for sharing this. Can you please explain the logic behind this solution?

• 给定一个二进制数组，求其中满足`0的个数与1的个数相等`的最长子数组
首先，将原始数组nums中的0替换为-1
然后不断的加sum, 如果两个sum值一样，说明这两个sum之间刚好有相同的-1和1也就是相同的0和1. 然后算距离就行了。
唯一注意的为了算最长距离，我们不会一直更新map，只有这个sum没出现的时候才添加。

``````    public int findMaxLength(int[] nums) {

Map<Integer, Integer> map = new HashMap();
map.put(0, -1);
int res = 0, sum = 0;
for(int i = 0; i < nums.length; i++){
sum += nums[i] == 0 ? -1 : 1;
if(map.containsKey(sum)){
res = Math.max(res, i - map.get(sum));
} else {
map.put(sum, i);
}
}
return res;
}``````

• It can be further simplified by using just one number to record the number of diffs
`zero > 0` means we have more zeros than ones
`zero < 0` means we have more ones than zeros
`zero == 0` means we have equal number of ones and zeros
For example, if at any index `i` we have `zero = 1`, then we have 1 diff (1 more 0s than 1s), we record it in the HashMap, and if later at index `j` we meet another situation that `zero = 1`, this means from the index `i` till the index `j`, the number of 0s and 1s are the same.

``````public class Solution {
public int findMaxLength(int[] nums) {
Map<Integer, Integer> map = new HashMap<>();
int max = 0;
int zero = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] == 0) zero++;
else zero--;
if (zero == 0) max = i + 1;
if (!map.containsKey(zero)) map.put(zero, i);
else max = Math.max(max, i - map.get(zero));
}
return max;
}
}
``````

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.