-
Notifications
You must be signed in to change notification settings - Fork 7
/
Main.java
53 lines (45 loc) · 1.13 KB
/
Main.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
package com.company;
import java.util.*;
public class Main {
public static void main(String[] args) {
var set = new RandomizedSet();
set.insert(0);
set.insert(1);
set.remove(0);
set.insert(2);
set.remove(1);
set.getRandom();
}
}
class RandomizedSet {
List<Integer> nums;
Map<Integer, Integer> map;
Random random;
public RandomizedSet() {
nums = new ArrayList<>();
map = new HashMap<>();
random = new Random();
}
public boolean insert(int val) {
if (map.containsKey(val))
return false;
nums.add(val);
map.put(val, nums.size() - 1);
return true;
}
public boolean remove(int val) {
if (!map.containsKey(val))
return false;
int index = map.get(val);
int last = nums.get(nums.size() - 1);
nums.set(index, last);
nums.remove(nums.size() - 1);
map.put(last, index);
map.remove(val);
return true;
}
public int getRandom() {
int index = random.nextInt(nums.size());
return nums.get(index);
}
}