LeetCode 560. 和为 K 的子数组

题目描述

🔥 560. 和为 K 的子数组

image-20230307193937587

思路分析

前缀和+哈希表

参考代码

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
}

🍏 点击查看 Java 题解

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;
    }
}

相似题目

题目 难度 题解
两数之和 Easy  
连续的子数组和 Medium  
乘积小于 K 的子数组 Medium  
寻找数组的中心下标 Easy  
和可被 K 整除的子数组 Medium  
本文作者:
本文链接: https://hgnulb.github.io/blog/13096231
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议,转载请注明出处!