-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSubarraySumEqualsK_560.java
More file actions
39 lines (36 loc) · 1010 Bytes
/
Copy pathSubarraySumEqualsK_560.java
File metadata and controls
39 lines (36 loc) · 1010 Bytes
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
package Array;
import java.util.HashMap;
/**
* 求连续子数组和为k的个数,不是排序数组,有正有负
*/
public class SubarraySumEqualsK_560 {
//利用哈希表
public int subarraySum(int[] nums, int k) {
HashMap<Integer,Integer> map=new HashMap<>();
int count=0;
int sum=0;
map.put(0,1);
for (int num : nums) {
sum += num;
if (map.containsKey(sum - k))
count += map.get(sum - k);
if (map.containsKey(sum)) {
map.put(sum, map.get(sum) + 1);
} else
map.put(sum, 1);
}
return count;
}
public int subarraySum_1(int[] nums, int k) {
int count=0;
for(int i=0;i<nums.length;i++){
int temp=nums[i];
if(temp==k) count++;
for(int j=i+1;j<nums.length;j++){
temp+=nums[j];
if(temp==k) count++;
}
}
return count;
}
}