-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
0380-insert-delete-getrandom-o1.java
57 lines (47 loc) · 1.6 KB
/
0380-insert-delete-getrandom-o1.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
class RandomizedSet {
private Map<Integer, Integer> indexing;
private List<Integer> numbers;
public RandomizedSet() {
this.indexing = new HashMap<>();
this.numbers = new ArrayList<>();
}
// Append to the end, maintain indexing
// Delete by swapping with the end, maintain indexing
// Get random by getting a random index wrt list's size
public boolean insert(int val) {
if(this.indexing.containsKey(val)) {
return false;
}
int indexInsert = this.numbers.size();
this.numbers.add(val);
this.indexing.put(val, indexInsert);
return true;
}
public boolean remove(int val) {
if(!this.indexing.containsKey(val)) {
return false;
}
int lastIndex = this.numbers.size() - 1;
int lastElement = this.numbers.get(lastIndex);
int indexElement = this.indexing.get(val);
// Swap with last element
this.numbers.set(indexElement, lastElement);
// Update indices [Add & Delete]
this.indexing.put(lastElement, indexElement);
this.indexing.remove(val);
// Remove from list
this.numbers.remove(lastIndex);
return true;
}
public int getRandom() {
int randomIndex = (int) (Math.random() * this.numbers.size());
return this.numbers.get(randomIndex);
}
}
/**
* Your RandomizedSet object will be instantiated and called as such:
* RandomizedSet obj = new RandomizedSet();
* boolean param_1 = obj.insert(val);
* boolean param_2 = obj.remove(val);
* int param_3 = obj.getRandom();
*/