Skip to content

Commit 5e9b951

Browse files
committed
fd
1 parent 93e0c52 commit 5e9b951

File tree

2 files changed

+12
-46
lines changed

2 files changed

+12
-46
lines changed

leetcode/solution/src/SubarraySumEqualsK.java

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,13 +8,16 @@ public class SubarraySumEqualsK {
88

99
/**
1010
* 注意map.put(0,1),即当前数自己也算是一种
11+
* TestCase [1], 0,即k=0的情况
1112
*/
1213
public int subarraySum(int[] nums, int k) {
1314
HashMap<Integer, Integer> map = new HashMap<>();
1415
map.put(0, 1);
1516
int count = 0;
1617
for (int i = 0, sum = 0; i < nums.length; i++) {
1718
sum += nums[i];
19+
// 以下两句顺序非常重要,因为两个差要至少相差一个数以上,因此不能刚给当前sum放到Map就参与运算
20+
// 比如k=0,如果刚给sum放到map就参与运算,那么sum-sum=0的情况是非法的
1821
count += map.getOrDefault(sum - k, 0);
1922
map.put(sum, map.getOrDefault(sum, 0) + 1);
2023
}

leetcode/src/Main.java

Lines changed: 9 additions & 46 deletions
Original file line numberDiff line numberDiff line change
@@ -4,53 +4,16 @@ public class Main {
44

55
public static class Solution {
66

7-
8-
}
9-
10-
class RandomizedSet {
11-
12-
ArrayList<Integer> list;
13-
HashMap<Integer, Integer> map;
14-
Random random;
15-
16-
/** Initialize your data structure here. */
17-
public RandomizedSet() {
18-
map = new HashMap<>();
19-
list = new ArrayList<>();
20-
random = new Random();
21-
}
22-
23-
/** Inserts a value to the set. Returns true if the set did not already contain the specified element. */
24-
public boolean insert(int val) {
25-
if (map.containsKey(val)) {
26-
return false;
7+
public int subarraySum(int[] nums, int k) {
8+
HashMap<Integer, Integer> map = new HashMap<>();
9+
map.put(0, 1);
10+
int count = 0;
11+
for (int i = 0, sum = 0; i < nums.length; i++) {
12+
sum += nums[i];
13+
map.put(sum, map.getOrDefault(sum, 0) + 1);
14+
count += map.getOrDefault(sum - k, 0);
2715
}
28-
list.add(val);
29-
map.put(val, list.size() - 1);
30-
return true;
31-
}
32-
33-
/** Removes a value from the set. Returns true if the set contained the specified element. */
34-
public boolean remove(int val) {
35-
int index = map.getOrDefault(val, -1);
36-
if (index < 0) {
37-
return false;
38-
}
39-
if (index != list.size() - 1) {
40-
int tail = list.get(list.size() - 1);
41-
list.set(index, tail);
42-
map.put(tail, index);
43-
}
44-
map.remove(val);
45-
list.remove(list.size() - 1);
46-
return true;
47-
}
48-
49-
/** Get a random element from the set. */
50-
public int getRandom() {
51-
int index = random.nextInt() % list.size();
52-
index = (index >= 0 ? index : -index);
53-
return list.get(index);
16+
return count;
5417
}
5518
}
5619

0 commit comments

Comments
 (0)