@@ -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