[LeetCode] 560. 和为K的子数组

前缀和问题。题目很好理解,读完题我们可以很迅速的想到利用前缀和实现O(n^2)的算法

其实,题目要求只统计满足k的子序列个数。所以当我们遍历到i时,prefix[i] + x = k,所以我们只需要知道x这个值出现了几次,就能统计出i节点所能构成的答案。借用Map结构就能很轻易得到。

最终一次遍历就能统计出来。

这个方法自己没想到,看题解学来的。妙啊,实在是妙啊

560. 和为K的子数组

public 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 i = 0; i < nums.length; i++) {
            pre += nums[i];
            if (mp.containsKey(pre - k)) {
                count += mp.get(pre - k);
            }
            mp.put(pre, mp.getOrDefault(pre, 0) + 1);
        }
        return count;
    }
}
原文地址:https://www.cnblogs.com/acbingo/p/14856927.html