[Leetcode] 力扣560:和为K的子数组

在这里插入图片描述
思路
涉及到子数组元素和问题,首先想到前缀和方法(空间换时间的方法)

class Solution {
    
    
public:
    int subarraySum(vector<int>& nums, int k) {
    
    
        unordered_map<int, int> hash;
        int preSum = 0;
        int res = 0;
        hash[0] = 1;   //和为0的前缀和目前有一个
        for (int& n:nums) {
    
    
            preSum += n;
            res += hash[preSum - k];
            hash[preSum] ++;
        }
        return res;
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_44537258/article/details/112693785