525. 连续数组

剑指 Offer II 011. 0 和 1 个数相同的子数组open in new window

Approach 1,前缀和+哈希表

class Solution {
    public int findMaxLength(int[] nums) {
        int sum = 0;
        int max = 0;
        Map<Integer, Integer> map = new HashMap<>();
        map.put(0, -1);
        for (int i = 0; i < nums.length; i++) {
            sum += nums[i] == 0 ? -1 : 1;
            Integer preIndex = map.get(sum);
            if (preIndex == null) {
                map.put(sum, i);
            } else {
                max = Math.max(max, i - preIndex);
            }
        }
        return max;
    }
}
Last Updated:
Contributors: jesse