題目要求
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.
Example:
// 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();
設計一個數據結構,使得能夠在O(1)的時間複雜度中插入數字,刪除數字,以及隨機獲取一個數字。要求所有的數字都能夠被等概率的隨機出來。
思路和代碼
其實有幾個思路入手:
如何實現O(1)的插入
這裏數字的插入還需要能夠去重,即需要首先判斷該數字是否已經存在,已經存在的話就不執行任何插入操作。如果底層是一個一般的數組,我們知道查詢的時間複雜度爲O(n),明顯不滿足題目的意思。一個有序的數組能夠將查詢的時間複雜度下降到O(lgn),但是這依然不滿足條件1,而且也無法做到所有的元素被等概率的查詢出來,因爲每插入一個元素都將改動之前元素的位置。而唯一能夠做到O(1)時間查詢的只有一個數據結構,即hash。因此,使用hash來查詢時不可避免的。
如何實現O(1)的刪除
這個其實是一個很經典的問題了,只要能夠利用hash在O(1)的時間內找到這個數字的位置,就有兩種方法來實現O(1)的刪除,一個是利用僞刪除,即每一個位置都對應一個狀態爲,將狀態位社會爲已經刪除即可,還有一種就更有意思,就是將被刪除位替換爲數組最後一位的值,然後只需要刪除最後一位就行。這種刪除就無需將刪除位右側的元素全部左移造成O(n)的時間複雜度。這裏我們採用的是第二種方法。
如何實現O(1)的隨機查詢
這個其實就是強調一點,我們需要維持原有的插入順序,從而保證各個元素等概率被隨機。
綜上所述,我們底層需要兩種數據結構,一個hashmap來支持O(1)的查詢,以及一個list來支持隨機數的獲取。代碼實現如下:
public class InsertDeleteGetRandom_380 {
private List<Integer> list;
private Map<Integer, Integer> hash;
public InsertDeleteGetRandom_380() {
list = new ArrayList<Integer>();
hash = new HashMap<Integer, Integer>();
}
/** Inserts a value to the set. Returns true if the set did not already contain the specified element. */
public boolean insert(int val) {
if(hash.containsKey(val)) {
return false;
}
list.add(val);
hash.put(val, list.size()-1);
return true;
}
/** Removes a value from the set. Returns true if the set contained the specified element. */
public boolean remove(int val) {
if(!hash.containsKey(val)){
return false;
}
int position = hash.get(val);
if(position != list.size()-1) {
int last = list.get(list.size()-1);
list.set(position, last);
hash.put(last, position);
}
list.remove(list.size()-1);
hash.remove(val);
return true;
}
/** Get a random element from the set. */
public int getRandom() {
int position = (int)Math.floor((Math.random() * list.size()));
return list.get(position);
}
}