题目
解法1:TLE
class Solution {
public:int subarraySum(vector<int>& nums, int k) {
int curr_sum;int count = 0;for(int i=0;i<nums.size();i++){
curr_sum = 0;for(int j=i;j<nums.size();j++){
curr_sum += nums[j];if(curr_sum == k){
count += 1;}}}return count;}
};
解法2:
class Solution {
public:int subarraySum(vector<int>& nums, int k) {
unordered_map<int,int> seen;seen[0] += 1;int curr_sum = 0;int count = 0;for(int i=0;i<nums.size();i++){
curr_sum += nums[i];if(seen.find(curr_sum-k) != seen.end()){
count += seen[curr_sum-k];}seen[curr_sum] += 1;}return count;}
};