LeetCode 560. 和为 K 的子数组
题目描述
思路分析
前缀和+哈希表
参考代码
1
2
3
4
5
6
7
8
9
10
11
12
13
func subarraySum(nums []int, k int) int {
hashtable := make(map[int]int)
hashtable[0] = 1
res, total := 0, 0
for _, num := range nums {
total += num
if count, ok := hashtable[total-k]; ok {
res += count
}
hashtable[total]++
}
return res
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public int subarraySum(int[] nums, int k) {
Map<Integer, Integer> map = new HashMap<>();
map.put(0, 1);
int total = 0;
int res = 0;
for (int num : nums) {
total += num;
res += map.getOrDefault(total - k, 0);
map.put(total, map.getOrDefault(total, 0) + 1);
}
return res;
}
}
CC BY-NC-SA 4.0
许可协议,转载请注明出处!
本博客所有文章除特别声明外,均采用