File tree Expand file tree Collapse file tree 1 file changed +50
-0
lines changed Expand file tree Collapse file tree 1 file changed +50
-0
lines changed Original file line number Diff line number Diff line change 1+ class RandomizedSet {
2+ HashMap <Integer , Integer > hm ;
3+ ArrayList <Integer > keys ;
4+ Random generator ;
5+
6+ /** Initialize your data structure here. */
7+ public RandomizedSet () {
8+ hm = new HashMap <Integer , Integer >();
9+ keys = new ArrayList <Integer >();
10+ generator = new Random ();
11+ }
12+
13+ /**
14+ * Inserts a value to the set. Returns true if the set did not already contain
15+ * the specified element.
16+ */
17+ public boolean insert (int val ) {
18+ boolean contains = hm .containsKey (val );
19+
20+ if (contains ) {
21+ return false ;
22+ }
23+
24+ keys .add (val );
25+ hm .put (val , hm .getOrDefault (val , 0 ) + 1 );
26+ return true ;
27+ }
28+
29+ /**
30+ * Removes a value from the set. Returns true if the set contained the specified
31+ * element.
32+ */
33+ public boolean remove (int val ) {
34+ boolean contains = hm .containsKey (val );
35+
36+ if (!contains ) {
37+ return false ;
38+ }
39+
40+ keys .remove (new Integer (val ));
41+ hm .remove (val );
42+ return true ;
43+ }
44+
45+ /** Get a random element from the set. */
46+ public int getRandom () {
47+ ;
48+ return keys .get (generator .nextInt (hm .size ()));
49+ }
50+ }
You can’t perform that action at this time.
0 commit comments