|
1 | 1 | class RandomizedSet {
|
2 | 2 |
|
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; |
12 | 5 |
|
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<>(); |
16 | 9 | }
|
17 |
| - this.randomizedSet.add(val); |
18 |
| - this.indexMap.put(val, this.currSize++); |
19 |
| - return true; |
20 |
| - } |
21 | 10 |
|
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; |
25 | 18 | }
|
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 |
| - } |
34 | 19 |
|
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 | + } |
38 | 39 | }
|
39 | 40 |
|
40 | 41 | /**
|
|
0 commit comments