Poison

525. Contiguous Array

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
public int findMaxLength(int[] nums) {
int preSum = 0, maxLength = 0;
Map<Integer, Integer> preSumToLastIndexMap = new HashMap<>();
preSumToLastIndexMap.put(0, -1);
for (int i = 0; i < nums.length; i++) {
int num = nums[i];
preSum += num == 0 ? -1 : 1;

// 当 preSum 再次出现时,说明出现了次数相等的 0 和 1
Integer lastIndex = preSumToLastIndexMap.get(preSum);
if (lastIndex == null) {
preSumToLastIndexMap.put(preSum, i);
} else {
maxLength = Math.max(maxLength, i - lastIndex);
}
}

return maxLength;
}
}
Reference

525. Contiguous Array
剑指 Offer II 011. 0 和 1 个数相同的子数组