力扣 560. 和为 K 的子数组

154 阅读1分钟

🔗 leetcode.cn/problems/su…

题目

  • 给一个由 int 组成的数组,给定数字 k
  • 返回子数组求和等于 k 的个数

思路

  • 统计并记录 presum 出现的频次 mp[presum] = freq
  • 当遍历至当前 presum 时,能够满足 sum 为 k 的子数组的个数为 mp[presum -k]
  • 更新当前 presum 的频次

代码

class Solution {
public:
    int subarraySum(vector<int>& nums, int k) {
        unordered_map<int,int> mp;
        int pre_sum = 0;
        mp[pre_sum] = 1;
        int count = 0;
        for (int i = 0; i < nums.size(); i++) {
            pre_sum += nums[i];
            if (mp.find(pre_sum - k) != mp.end()) count += mp[pre_sum - k];
            mp[pre_sum]++;
        }
        return count;
    }
};