forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path_380.java
58 lines (50 loc) · 1.85 KB
/
_380.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
package com.fishercoder.solutions;
import java.util.HashMap;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.Random;
public class _380 {
public static class Solution1 {
/**
* credit: https://leetcode.com/problems/insert-delete-getrandom-o1/discuss/85401/Java-solution-using-a-HashMap-and-an-ArrayList-along-with-a-follow-up.-(131-ms)
*/
public static class RandomizedSet {
Map<Integer, Integer> map;
List<Integer> list;
Random random;
public RandomizedSet() {
map = new HashMap<>();
random = new Random();
list = new ArrayList<>();
}
public boolean insert(int val) {
if (map.containsKey(val)) {
return false;
}
map.put(val, list.size());
list.add(list.size(), val);
return true;
}
public boolean remove(int val) {
if (!map.containsKey(val)) {
return false;
} else {
int removeIndex = map.get(val);
if (removeIndex != list.size() - 1) {
//if it's not the last element, then we need to swap it with the last element so that this operation is also O(1)
int lastElement = list.get(list.size() - 1);
list.set(removeIndex, lastElement);
map.put(lastElement, removeIndex);
}
map.remove(val);
list.remove(list.size() - 1);
return true;
}
}
public int getRandom() {
return list.get(random.nextInt(list.size()));
}
}
}
}