当前位置: 代码迷 >> 综合 >> Leetcode 560. Subarray Sum Equals K (cpp)
  详细解决方案

Leetcode 560. Subarray Sum Equals K (cpp)

热度:27   发布时间:2023-11-26 06:02:50.0

题目

在这里插入图片描述

解法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;}
};
  相关解决方案