-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path560. 和为K的子数组.java
More file actions
45 lines (43 loc) · 1.12 KB
/
Copy path560. 和为K的子数组.java
File metadata and controls
45 lines (43 loc) · 1.12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
/**
* O(n^2)
*/
// class Solution {
// public int subarraySum(int[] nums, int k) {
// int sum = 0;
// int count = 0;
// for(int i = 0; i < nums.length; i++){
// sum += nums[i];
// if(sum == k){
// count++;
// }
// for(int j = i + 1; j < nums.length; j++){
// sum += nums[j];
// if(sum == k){
// count++;
// }
// }
// sum = 0;
// }
// return count;
// }
// }
/**
* O(n)
*/
class Solution {
public int subarraySum(int[] nums, int k) {
int sum = 0;
int count = 0;
Map<Integer, Integer> hashMap = new HashMap<>(); // key存的是sum,value存的是个数
hashMap.put(0, 1); // 因为最少是1个
for(int i = 0; i < nums.length; i++){
sum += nums[i];
if(hashMap.containsKey(sum - k)){
count += hashMap.get(sum - k);
}
hashMap.put(sum, hashMap.getOrDefault(sum, 0) + 1);
}
return count;
}
}
// 0 0 0 0 0 0 0 0 0 0