跳转至

和为K的子数组⚓︎

Leetcode题目链接

描述⚓︎

详见中文题目链接

解答⚓︎

class Solution {
public:
    int subarraySum(vector<int>& nums, int k) {
        unordered_map<int, int> sumToCount;
        sumToCount[0] = 1;
        int count = 0, prefixSum = 0;

        for (int x : nums) {
            prefixSum += x;
            if (sumToCount.find(prefixSum - k) != sumToCount.end()) {
                count += sumToCount[prefixSum - k];
            }
            sumToCount[prefixSum]++;
        }

        return count;
    }
};