Leetcode380 Insert Delete GetRandom O(1)

题目描述

Design a data structure that supports all following operations in average O(1) time.

insert(val): Inserts an item val to the set if not already present.
remove(val): Removes an item val from the set if present.
getRandom: Returns a random element from current set of elements. Each element must have the same probability of being returned.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// Init an empty set.
RandomizedSet randomSet = new RandomizedSet();

// Inserts 1 to the set. Returns true as 1 was inserted successfully.
randomSet.insert(1);

// Returns false as 2 does not exist in the set.
randomSet.remove(2);

// Inserts 2 to the set, returns true. Set now contains [1,2].
randomSet.insert(2);

// getRandom should return either 1 or 2 randomly.
randomSet.getRandom();

// Removes 1 from the set, returns true. Set now contains [2].
randomSet.remove(1);

// 2 was already in the set, so return false.
randomSet.insert(2);

// Since 2 is the only number in the set, getRandom always return 2.
randomSet.getRandom();

解析

这是一道很有意思的设计问题,美国的面试中这种设计问题并不少见,主要考察对数据结构的灵活运用与组合,一般涉及到两个数据结构的组合。

题意十分简单,设计一个数据结构,RandomSet随机集合,支持O(1)时间的插入、删除和获取随机值的操作。

前两个操作十分简单,用HashMap或者HashSet即可,O(1)的随机获取,可以使用顺序表,Java里是ArrayList,C++里是vector,所以我们应该利用这两个的组合来设计RandomSet。

一个显然的思路是用HashMap存val与ArrayList里val的index的对应关系,获取随机数时再用ArrayList, 不过如果直接这样写会报错,因为每次删除数据时ArrayList的长度会改变,HashMap里存储的index就失去了效果,然而如果每次删除某个Index将后面的所有的index - 1,再在HashMap里都修改一遍,则时间复杂度就不再是O(1)了,那么有没有什么更好的办法。

这里有一个比较Tricky的办法,也是我个人认为这道题的灵魂所在,因为这道题本质是一个Set,所以数字的顺序我们并不关心,我们就在删除时把所需要删除的元素与ArrayList里最后一个元素交换,然后每次默认只删除最后一个元素,这样其他index则不再改变,Map每次只修改原先的LastIndex所对应的val的index即可。

Talk is Cheap, Show your the code:

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
class RandomizedSet {
HashMap<Integer, Integer> indexMap;
ArrayList<Integer> set;
/** Initialize your data structure here. */
public RandomizedSet() {
indexMap = new HashMap<>();
set = 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(indexMap.containsKey(val))
return false;
indexMap.put(val, set.size());
set.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(!indexMap.containsKey(val))
return false;
int index = indexMap.get(val);
// 在ArrayList中,交换最后一个index
if(index != set.size() - 1){
int lastNum = set.get(set.size() - 1);
set.set(index, lastNum);
indexMap.put(lastNum, index);
}
indexMap.remove(val);
set.remove(set.size() - 1);
return true;
}

/** Get a random element from the set. */
public int getRandom() {
Random random = new Random();
int index = random.nextInt(set.size());
return set.get(index);
}
}

有一个follow up是如果允许multiple values怎么办,把map对应index从一对一改为一对多,即将HashMap的key改成HashSet即可