leetcode-560-和为k的子数组

 

 方法:前缀和 + 哈希表 O(N)

class Solution {
    public int subarraySum(int[] nums, int k) {
        int count = 0,pre = 0;
        HashMap <Integer,Integer> mp = new HashMap<> ();
        mp.put(0,1);
        for (int num:nums){
            pre += num;
            if (mp.containsKey(pre -k)){
                count += mp.get(pre - k);
            }
            mp.put(pre,mp.getOrDefault(pre,0) + 1);
        }
        return count;
    }
}

 

posted @ 2020-05-15 21:05  oldby  阅读(122)  评论(0编辑  收藏  举报