-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathRandomizedSet.java
More file actions
49 lines (44 loc) · 1.03 KB
/
Copy pathRandomizedSet.java
File metadata and controls
49 lines (44 loc) · 1.03 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
import java.util.*;
public class RandomizedSet
{
List<Integer> list;
Map<Integer, Integer> indices;
public RandomizedSet()
{
list = new ArrayList<>();
indices = new HashMap<>();
}
public boolean insert(int val)
{
if (!indices.containsKey(val))
{
indices.put(val, list.size());
list.add(val);
return true;
}
return false;
}
public boolean remove(int val)
{
if (indices.containsKey(val))
{
int idx = indices.get(val);
list.set(idx, list.get(list.size() - 1));
indices.put(list.get(list.size() - 1), idx);
indices.remove(val);
list.remove(list.size() - 1);
return true;
}
return false;
}
/**
* Get a random element from the set.
*/
public int getRandom()
{
Random rand = new Random();
int len = list.size();
int idx = rand.nextInt(len);
return list.get(idx);
}
}