地址:https://leetcode-cn.com/problems/contiguous-array/
题解:https://leetcode-cn.com/problems/contiguous-array/solution/qian-zhui-he-chai-fen-ha-xi-biao-java-by-liweiwei1/
Java 代码:
import java.util.HashMap;
import java.util.Map;
public class Solution {
public int findMaxLength(int[] nums) {
int len = nums.length;
Map<Integer, Integer> map = new HashMap<>();
map.put(0, -1);
int res = 0;
int preSum = 0;
// 把数组中的 0 都看成 -1
for (int i = 0; i < len; i++) {
if (nums[i] == 1) {
preSum += 1;
} else {
preSum += -1;
}
if (map.containsKey(preSum)) {
res = Math.max(res, i - map.get(preSum));
} else {
// 只记录这个数字第 1 次出现的下标
map.put(preSum, i);
}
}
return res;
}
}
有一题跟这个很像,并且还用到了状态压缩。
相关问题:
- 「力扣」第 560 题:和为K的子数组;
- 「力扣」第 974题:和可被 K 整除的子数组。