Leetcode Answers 380

继续刷题,昨晚看面经有很多设计方向的题,就多去看了几眼,所以并没刷太多。今天第一道是实现O(1)的各种method的题。

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

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

Example:

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();

思路:
当看到average O(1)的时候,大概就明白这道题怎么说都要和Hash沾边了。首先看要求的三个是insert,remove,和getRandom,并没有提到必须按插入顺序存放,其次要求average O(1),那也就是要amortized constant time即可。那么首先,肯定是Array最方便,凭借index就可以constant time access。但是index存在哪?Dictionary,因为是HashTable所以也是constant time access。那么Remove怎么办?换个思路,List在Remove头尾的时候是效率最高的,那么无论是remove哪个数字,把末尾的位置的数字换过去,然后去掉末尾的数字就好了。至于random,反正用index就是快。于是问题解决了。

Answer:

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
public class RandomizedSet {
List<int> list;
Dictionary<int, int> dict;
Random rnd;
/** Initialize your data structure here. */
public RandomizedSet() {
list = new List<int>();
dict = new Dictionary<int, int>();
rnd = new Random();
}
/** Inserts a value to the set. Returns true if the set did not already contain the specified element. */
public bool Insert(int val) {
if(!dict.ContainsKey(val)){
list.Add(val);
dict.Add(val, list.Count - 1);
return true;
}
return false;
}
/** Removes a value from the set. Returns true if the set contained the specified element. */
public bool Remove(int val) {
if(dict.ContainsKey(val)){
int last = list[list.Count - 1];
int idx = dict[val];
list[idx] = last;
list.RemoveAt(list.Count - 1);
dict[last] = idx;
dict.Remove(val);
return true;
}
return false;
}
/** Get a random element from the set. */
public int GetRandom() {
return list[rnd.Next(list.Count)];
}
}
/**
* Your RandomizedSet object will be instantiated and called as such:
* RandomizedSet obj = new RandomizedSet();
* bool param_1 = obj.Insert(val);
* bool param_2 = obj.Remove(val);
* int param_3 = obj.GetRandom();
*/

考察:这里C#的Random要注意是要在constructor里就instantiate的,不然会因为seed相同而导致数列全一致,到时候输出的数字都一样就很尴尬了。

以上。

17-04-27
@Sturbridge