Skip to content

Commit c370f8f

Browse files
Sean PrashadSean Prashad
authored andcommitted
Add 380_Insert_Delete_GetRandom_O(1).java
1 parent 97634bf commit c370f8f

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
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+
}

0 commit comments

Comments
 (0)