Skip to content

Commit 509b60f

Browse files
authored
Update Insert Delete GetRandom O(1).java
1 parent 290f75f commit 509b60f

File tree

1 file changed

+31
-30
lines changed

1 file changed

+31
-30
lines changed

Medium/Insert Delete GetRandom O(1).java

Lines changed: 31 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -1,40 +1,41 @@
11
class RandomizedSet {
22

3-
private List<Integer> randomizedSet;
4-
private Map<Integer, Integer> indexMap;
5-
private int currSize;
6-
7-
public RandomizedSet() {
8-
this.randomizedSet = new ArrayList<>();
9-
this.indexMap = new HashMap<>();
10-
this.currSize = 0;
11-
}
3+
private final List<Integer> values;
4+
private final Map<Integer, Integer> valToIndexMap;
125

13-
public boolean insert(int val) {
14-
if (this.indexMap.containsKey(val)) {
15-
return false;
6+
public RandomizedSet() {
7+
this.values = new ArrayList<>();
8+
this.valToIndexMap = new HashMap<>();
169
}
17-
this.randomizedSet.add(val);
18-
this.indexMap.put(val, this.currSize++);
19-
return true;
20-
}
2110

22-
public boolean remove(int val) {
23-
if (!this.indexMap.containsKey(val)) {
24-
return false;
11+
public boolean insert(int val) {
12+
if (valToIndexMap.containsKey(val)) {
13+
return false;
14+
}
15+
values.add(val);
16+
valToIndexMap.put(val, values.size() - 1);
17+
return true;
2518
}
26-
int valIdx = this.indexMap.get(val);
27-
this.indexMap.put(this.randomizedSet.get(this.currSize - 1), valIdx);
28-
this.randomizedSet.set(valIdx, this.randomizedSet.get(this.currSize - 1));
29-
this.randomizedSet.remove(this.currSize - 1);
30-
this.indexMap.remove(val);
31-
this.currSize--;
32-
return true;
33-
}
3419

35-
public int getRandom() {
36-
return this.randomizedSet.get(new Random().nextInt(this.currSize));
37-
}
20+
public boolean remove(int val) {
21+
if (!valToIndexMap.containsKey(val)) {
22+
return false;
23+
}
24+
int valIdx = valToIndexMap.get(val);
25+
int valAtLastIdx = values.get(values.size() - 1);
26+
// update index for last element
27+
values.set(valIdx, valAtLastIdx);
28+
valToIndexMap.put(valAtLastIdx, valIdx);
29+
// remove value
30+
values.remove(values.size() - 1);
31+
valToIndexMap.remove(val);
32+
return true;
33+
}
34+
35+
public int getRandom() {
36+
int idx = new Random().nextInt(values.size());
37+
return values.get(idx);
38+
}
3839
}
3940

4041
/**

0 commit comments

Comments
 (0)