和为K的子数组

给定一个整数数组和一个整数 k,你需要找到该数组中和为 k 的连续的子数组的个数。

示例 1 :

输入:nums = [1,1,1], k = 2
输出: 2 , [1,1] 与 [1,1] 为两种不同的情况。
说明 :

数组的长度为 [1, 20,000]。
数组中元素的范围是 [-1000, 1000] ,且整数 k 的范围是 [-1e7, 1e7]。

 

#include <iostream>
#include <vector>
#include <unordered_map>

using namespace std;

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

int main() {
    vector<int> nums = {1, 1, 1};
    Solution s;
    cout << s.subarraySum(nums, 2) << endl;
}

 

posted on 2021-02-24 19:15  QzZq  阅读(109)  评论(0)    收藏  举报

导航