「力扣」第 525 題:連續數組(前綴和 + 哈希表,把 0 看成 -1)

地址: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 整除的子數組。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章