Files
LeetCode/子串/1. 和为K的子数组.md
T
2025-09-29 21:28:21 +08:00

59 lines
1018 B
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 和为 K 的子数组
## 题目
给你一个整数数组 nums 和一个整数 k ,请你统计并返回 该数组中和为 k 的子数组的个数 。
子数组是数组中元素的连续非空序列。
示例 1:
输入:nums = [1,1,1], k = 2
输出:2
示例 2:
输入:nums = [1,2,3], k = 3
输出:2
提示:
1 <= nums.length <= 2 * 104
-1000 <= nums[i] <= 1000
-107 <= k <= 107
## 思路
- 前缀和
- `prefixSum`
- 哈希表单次遍历
## 代码
```java
class Solution {
public int subarraySum(int[] nums, int k) {
// Init
// Prefix Sum
Map<Integer, Integer> map = new HashMap<>();
map.put(0, 1);
int ans = 0, pre = 0;
// Traverse
for (int i = 0; i < nums.length; i++) {
pre += nums[i];
// Judge
if (map.containsKey(pre - k)) {
ans += map.get(pre - k);
}
map.put(pre, map.getOrDefault(pre, 0) + 1);
}
return ans;
}
}
```