
g0501_0600.s0560_subarray_sum_equals_k.Solution.cpp Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of leetcode-in-all Show documentation
Show all versions of leetcode-in-all Show documentation
104 LeetCode algorithm problem solutions
// #Medium #Top_100_Liked_Questions #Array #Hash_Table #Prefix_Sum #Data_Structure_II_Day_5_Array
// #Big_O_Time_O(n)_Space_O(n) #2024_05_21_Time_54_ms_(92.60%)_Space_45_MB_(70.78%)
#include
#include
class Solution {
public:
int subarraySum(std::vector& nums, int k) {
int tempSum = 0;
int ret = 0;
std::unordered_map sumCount;
sumCount[0] = 1;
for (int num : nums) {
tempSum += num;
if (sumCount.find(tempSum - k) != sumCount.end()) {
ret += sumCount[tempSum - k];
}
if (sumCount.find(tempSum) != sumCount.end()) {
sumCount[tempSum]++;
} else {
sumCount[tempSum] = 1;
}
}
return ret;
}
};
© 2015 - 2025 Weber Informatics LLC | Privacy Policy