-
Notifications
You must be signed in to change notification settings - Fork 73
Expand file tree
/
Copy pathConstantTimeDS.java
More file actions
72 lines (64 loc) · 1.36 KB
/
ConstantTimeDS.java
File metadata and controls
72 lines (64 loc) · 1.36 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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package algorithm.basic;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
/**
* A data structure that support O(1) add, delete and get random.
*
*/
public class ConstantTimeDS {
private Map<Integer, Integer> index;
private List<Integer> array;
private int size;
private Random rnd;
public ConstantTimeDS() {
index = new HashMap<Integer, Integer>();
array = new ArrayList<Integer>();
size = 0;
rnd = new Random();
}
/**
* Add a value with O(1)
* @param val
*/
public void add(int val) {
Integer idx = index.get(val);
if (idx == null) {
index.put(val, size++);
if (size < array.size()) {
array.set(size, val);
}
else {
array.add(val);
}
}
}
/**
* Delete a value with O(1)
* @param val
*/
public void del(int val) {
Integer idx = index.get(val);
if (idx == null) {
return;
}
int lastVal = array.get(array.size() - 1);
array.set(idx, lastVal);
index.put(lastVal, idx); // update index
index.remove(val); // remove deleted val from array
--size;
}
/**
* Get a random number in O(1)
* @return
*/
public int getRandom() {
if (size == 0) {
return -1;
}
int idx = rnd.nextInt(size);
return array.get(idx);
}
}