-
Notifications
You must be signed in to change notification settings - Fork 0
/
RandomizedSet.java
59 lines (44 loc) · 1.39 KB
/
RandomizedSet.java
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
import java.util.*;
public class RandomizedSet {
List<Integer> randomSet;
public RandomizedSet() {
this.randomSet = new ArrayList<>();
}
public boolean insert(int val) {
if (this.randomSet.contains(val)) return false;
randomSet.add(val);
return true;
}
public boolean remove(int val) {
if (this.randomSet.contains(val)) {
this.randomSet.remove(val);
return true;
}
return false;
}
public int getRandom() {
int randomIndex = new Random().nextInt(this.randomSet.size());
int i = 0;
for (Integer integer : this.randomSet) {
if (i == randomIndex) {
return integer;
}
i++;
}
return 0;
}
public static void main(String[] args) {
RandomizedSet randomizedSet = new RandomizedSet();
randomizedSet.insert(3);
randomizedSet.insert(4);
randomizedSet.insert(6);
randomizedSet.insert(12);
System.out.println(randomizedSet.insert(1));
System.out.println(randomizedSet.remove(2));
System.out.println(randomizedSet.insert(2));
System.out.println(randomizedSet.getRandom());
System.out.println(randomizedSet.remove(1));
System.out.println(randomizedSet.insert(2));
System.out.println(randomizedSet.getRandom());
}
}