-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathm380.java
46 lines (40 loc) · 1.21 KB
/
m380.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
class RandomizedSet {
private ArrayList<Integer> vals;
private HashMap<Integer, Integer> indices;
public RandomizedSet() {
this.vals = new ArrayList<>();
this.indices = new HashMap<>();
}
public boolean insert(int val) {
if (this.indices.containsKey(val)) {
return false;
}
this.indices.put(val, this.vals.size());
this.vals.add(val);
return true;
}
public boolean remove(int val) {
if (!this.indices.containsKey(val)) {
return false;
}
int indx = this.indices.remove(val);
if (indx == vals.size() - 1) {
this.vals.removeLast();
} else {
int lastVal = this.vals.removeLast();
this.vals.set(indx, lastVal);
this.indices.put(lastVal, indx);
}
return true;
}
public int getRandom() {
return this.vals.get((int) (Math.random() * this.vals.size()));
}
}
/**
* 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();
*/