LeetCode-560. Subarray Sum Equals KLevel up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.https://leetcode.com/problems/subarray-sum-equals-k/
Given an array of integers?nums ?and an integer?k , return?the total number of subarrays whose sum equals to?k .
Example 1:
Input: nums = [1,1,1], k = 2
Output: 2
Example 2:
Input: nums = [1,2,3], k = 3
Output: 2
Constraints:
1 <= nums.length <= 2 * 10^4 -1000 <= nums[i] <= 1000 -10^7?<= k <= 10^7
【C++】
class Solution {
public:
int subarraySum(vector<int>& nums, int k) {
int count = 0, psum = 0;
unordered_map<int, int> hashmap;
hashmap[0] = 1; // 初始化很重要
for (int i: nums) {
psum += i;
count += hashmap[psum-k];
++hashmap[psum];
}
return count;
}
};
【Java】
class Solution {
public int subarraySum(int[] nums, int k) {
int count = 0, psum = 0;
Map<Integer, Integer> hashmap = new HashMap<>();
hashmap.put(0, 1); // 初始化很重要
for (int i: nums) {
psum += i;
count += hashmap.getOrDefault(psum - k, 0);
hashmap.put(psum, hashmap.getOrDefault(psum, 0) + 1);
}
return count;
}
}
|