Solutions to high-frequency interview questions of LeetCode in C++17, taking into account both efficiency and comprehensibility.
k
,则这两个位置的前缀和之差为 k
class Solution {
public:
int subarraySum(vector<int>& nums, int k) {
int res = 0;
int sum = 0;
unordered_map<int, int> m;
m[0] = 1;
for (auto& x : nums) {
sum += x;
if (m.count(sum - k)) {
res += m[sum - k];
}
++m[sum];
}
return res;
}
};