Insert Delete GetRandom O(1) LeetCode solution in Java

1
class RandomizedSet {
2
HashMap<Integer, Integer> map;
3
ArrayList<Integer> list;
4
Random rand;
5

6
public RandomizedSet() {
7
map = new HashMap<>();
8
list = new ArrayList<>();
9
rand = new Random();
10
}
11

12
public boolean insert(int val) {
13
if (!map.containsKey(val)) {
14
map.put(val, list.size());
15
list.add(val);
16
return true;
17
}
18
return false;
19
}
20

21
public boolean remove(int val) {
22
if (map.containsKey(val)) {
23
int index = map.get(val);
24
int last = list.get(list.size() - 1);
25
if (index != list.size() - 1) {
26
list.set(index, last);
27
map.put(last, index);
28
}
29
list.remove(list.size() - 1);
30
map.remove(val);
31
return true;
32
}
33
return false;
34
}
35

36
public int getRandom() {
37
int r = rand.nextInt(list.size());
38
return list.get(r);
39
}
40
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0