Skip to content

Commit bef98ba

Browse files
committed
leetcode
1 parent 9ddb4ee commit bef98ba

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
//给定一个整数数组和一个整数 k,你需要找到该数组中和为 k 的连续的子数组的个数。
2+
//
3+
// 示例 1 :
4+
//
5+
//
6+
//输入:nums = [1,1,1], k = 2
7+
//输出: 2 , [1,1] 与 [1,1] 为两种不同的情况。
8+
//
9+
//
10+
// 说明 :
11+
//
12+
//
13+
// 数组的长度为 [1, 20,000]。
14+
// 数组中元素的范围是 [-1000, 1000] ,且整数 k 的范围是 [-1e7, 1e7]。
15+
//
16+
// Related Topics 数组 哈希表
17+
18+
19+
package leetcode.editor.cn;
20+
21+
import java.util.HashMap;
22+
import java.util.Map;
23+
24+
public class _0560_SubarraySumEqualsK {
25+
26+
public static void main(String[] args) {
27+
Solution solution = new _0560_SubarraySumEqualsK().new Solution();
28+
}
29+
30+
//leetcode submit region begin(Prohibit modification and deletion)
31+
class Solution {
32+
33+
public int subarraySum(int[] nums, int k) {
34+
int cnt = 0, pre = 0;
35+
Map<Integer, Integer> map = new HashMap<>();
36+
map.put(0, 1);
37+
for (int n : nums) {
38+
pre += n;
39+
if (map.containsKey(pre - k)) {
40+
cnt += map.get(pre - k);
41+
}
42+
map.put(pre, map.getOrDefault(pre, 0) + 1);
43+
}
44+
return cnt;
45+
}
46+
}
47+
//leetcode submit region end(Prohibit modification and deletion)
48+
49+
}

0 commit comments

Comments
 (0)