-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path380.insert-delete-getrandom-o1.java
More file actions
57 lines (45 loc) · 1.44 KB
/
Copy path380.insert-delete-getrandom-o1.java
File metadata and controls
57 lines (45 loc) · 1.44 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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
class RandomizedSet {
HashMap<Integer, Integer> valueMap;
HashMap<Integer, Integer> idxMap;
/** Initialize your data structure here. */
public RandomizedSet() {
valueMap = new HashMap<>();
idxMap = new HashMap<>();
}
/** Inserts a value to the set. Returns true if the set did not already contain the specified element. */
public boolean insert(int val) {
if(valueMap.containsKey(val)){
return false;
}
valueMap.put(val, valueMap.size());
idxMap.put(idxMap.size(), val);
return true;
}
/** Removes a value from the set. Returns true if the set contained the specified element. */
public boolean remove(int val) {
if(valueMap.containsKey(val)){
int idx = valueMap.get(val);
valueMap.remove(val);
idxMap.remove(idx);
Integer tailElem = idxMap.get(idxMap.size());
if(tailElem!=null){
idxMap.put(idx,tailElem);
valueMap.put(tailElem, idx);
}
return true;
}
return false;
}
/** Get a random element from the set. */
public int getRandom() {
if(valueMap.size()==0){
return -1;
}
if(valueMap.size()==1){
return idxMap.get(0);
}
Random r = new Random();
int idx = r.nextInt(valueMap.size());
return idxMap.get(idx);
}
}