-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRandomizedSet.java
More file actions
39 lines (30 loc) · 871 Bytes
/
Copy pathRandomizedSet.java
File metadata and controls
39 lines (30 loc) · 871 Bytes
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
class RandomizedSet {
private ArrayList<Integer> list;
private Map<Integer, Integer> map;
public RandomizedSet() {
list = new ArrayList<>();
map = new HashMap<>();
}
public boolean search(int val) {
return map.containsKey(val);
}
public boolean insert(int val) {
if (search(val)) return false;
list.add(val);
map.put(val, list.size() - 1);
return true;
}
public boolean remove(int val) {
if (!search(val)) return false;
int index = map.get(val);
list.set(index, list.get(list.size() - 1));
map.put(list.get(index), index);
list.remove(list.size() - 1);
map.remove(val);
return true;
}
public int getRandom() {
Random rand = new Random();
return list.get(rand.nextInt(list.size()));
}
}