forked from singlemancombat/interview-preparation
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInsertDeleteGetRandom.java
More file actions
41 lines (36 loc) · 1.19 KB
/
Copy pathInsertDeleteGetRandom.java
File metadata and controls
41 lines (36 loc) · 1.19 KB
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
public class RandomizedSet {
List<Integer> nums;
Map<Integer, Integer> numToIndex;
Random random;
public RandomizedSet() {
nums = new ArrayList<>();
numToIndex = new HashMap<>();
random = new Random();
}
// Inserts a value to the set
// Returns true if the set did not already contain the specified element or false
public boolean insert(int val) {
if (numToIndex.containsKey(val)) return false;
nums.add(val);
numToIndex.put(val, nums.size() - 1);
return true;
}
// Removes a value from the set
// Return true if the set contained the specified element or false
public boolean remove(int val) {
if (!numToIndex.containsKey(val)) return false;
int pos = numToIndex.get(val);
if (pos != nums.size() - 1) {
int last = nums.get(nums.size() - 1);
nums.set(pos, last);
numToIndex.put(last, pos);
}
nums.remove(nums.size() - 1);
numToIndex.remove(val);
return true;
}
// Get a random element from the set
public int getRandom() {
return nums.get(random.nextInt(nums.size()));
}
}