LC.P380[O(1)时间插入、删除和获取随机元素]

方法一:Map+List

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
class RandomizedSet {

Map<Integer, Integer> map;
List<Integer> list;
Random random;

public RandomizedSet() {
map = new HashMap<>();
list = new ArrayList<>();
random = new Random();
}

public boolean insert(int val) {
if (map.containsKey(val)) return false;
map.put(val, list.size());
list.add(val);
return true;
}

public boolean remove(int val) {
if (!map.containsKey(val)) return false;
int size = list.size();
Integer lastVal = list.get(size - 1);
int index = map.get(val);
list.set(index, lastVal);
map.put(lastVal, index);
list.remove(size - 1);
map.remove(val);
return true;
}

public int getRandom() {
return list.get(random.nextInt(list.size()));
}
}

/**
* Your RandomizedSet object will be instantiated and called as such:
* RandomizedSet obj = new RandomizedSet();
* boolean param_1 = obj.insert(val);
* boolean param_2 = obj.remove(val);
* int param_3 = obj.getRandom();
*/
  • 时间复杂度:$O(1)$
  • 空间复杂度:$O(n)$