xinyu04

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

[Oracle] LeetCode 560 Subarray Sum Equals K 思维+Map

Given an array of integers nums and an integer k, return the total number of subarrays whose sum equals to k.

A subarray is a contiguous non-empty sequence of elements within an array.

Solution

我们需要找到所有的区间:

nums[i]+...+nums[j]=k

那么我们使用前缀和 prex[i]prex[j1]=k,那么转变一下:

prex[i]k=prex[j1]

所以同样也是 prex

点击查看代码
class Solution {
private:
unordered_map<int,int> mp;
int prex[20002];
public:
int subarraySum(vector<int>& nums, int k) {
int n = nums.size();
int ans=0;
prex[0]=nums[0];
for(int i=1;i<n;i++)prex[i]=nums[i]+prex[i-1];
for(int i=0;i<n;i++){
if(prex[i]==k)ans++;
if(mp.find(prex[i]-k)!=mp.end())ans+=mp[prex[i]-k];
mp[prex[i]]++;
}
return ans;
}
};

posted on   Blackzxy  阅读(14)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 因为Apifox不支持离线,我果断选择了Apipost!
· 通过 API 将Deepseek响应流式内容输出到前端
点击右上角即可分享
微信分享提示