-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathRandomizedSet.java
48 lines (39 loc) · 1.05 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
package leetcode.hashmap;
import java.util.*;
public class RandomizedSet {
HashMap<Integer, Integer> valIndex;
int[] nums;
int index;
Random random;
public RandomizedSet() {
this.valIndex = new HashMap<>();
this.nums = new int[200001];
this.index = 0;
this.random = new Random();
}
public boolean insert(int val) {
if (valIndex.containsKey(val)) {
return false;
} else {
nums[index] = val;
valIndex.put(val, index++);
return true;
}
}
public boolean remove(int val) {
if (valIndex.containsKey(val)) {
Integer originIndex = valIndex.remove(val);
if (originIndex != index - 1) {
nums[originIndex] = nums[index - 1];
valIndex.put(nums[index - 1], originIndex);
}
index--;
return true;
} else {
return false;
}
}
public int getRandom() {
return nums[random.nextInt(index)];
}
}