-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRandomizedSetResult.java
More file actions
63 lines (55 loc) · 1.85 KB
/
RandomizedSetResult.java
File metadata and controls
63 lines (55 loc) · 1.85 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
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* Author : WindAsMe
* File : RandomizedSetResult.java
* Time : Create on 18-9-7
* Location : ../Home/JavaForLeeCode2/RandomizedSetResult.java
* Function : LeetCode No.380
*/
public class RandomizedSetResult {
static class RandomizedSet {
private Set<Integer> set;
private List<Integer> list;
/** Initialize your data structure here. */
public RandomizedSet() {
set = new HashSet<>();
list = new ArrayList<>();
}
/** Inserts a value to the set. Returns true if the set did not already contain the specified element. */
public boolean insert(int val) {
if (set.contains(val))
return false;
else {
set.add(val);
list.add(val);
return true;
}
}
/** Removes a value from the set. Returns true if the set contained the specified element. */
public boolean remove(int val) {
if (set.contains(val)) {
list.remove(Integer.valueOf(val));
set.remove(val);
return true;
} else
return false;
}
/** Get a random element from the set. */
public int getRandom() {
return list.get((int)(Math.random() * list.size()));
}
}
public static void main(String[] args) {
RandomizedSet set = new RandomizedSet();
System.out.println(set.insert(1));
System.out.println(set.remove(2));
System.out.println(set.insert(2));
System.out.println(set.getRandom());
System.out.println(set.remove(1));
System.out.println(set.insert(2));
System.out.println(set.getRandom());
}
}