Java 代碼:
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class RandomizedSet {
/**
* 動態數組
*/
List<Integer> nums;
/**
* 用來建立每個數字和其在數組中的位置之間的對應關係
* key :真正插入的數值,方便以 O(1) 的時間複雜度實現 insert 和 remove 操作
* value:該值在數組 nums 中的下標
*/
Map<Integer, Integer> hashMap;
/**
* Initialize your data structure here.
*/
public RandomizedSet() {
nums = new ArrayList<>();
hashMap = new HashMap<>();
}
/**
* Inserts a value to the set. Returns true if the set did not already contain the specified element.
*/
public boolean insert(int val) {
if (hashMap.containsKey(val)) {
return false;
}
hashMap.put(val, nums.size());
// 添加在最後,這樣就是 O(1)
nums.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 (!hashMap.containsKey(val)) {
return false;
}
// 注意:這裏是很有技巧的地方
int index = hashMap.get(val);
// 如果這個數不在最後一位,就把本來最後一位應該放置的數字放到這個數的位置上,然後賦值
if (index < nums.size() - 1) {
int lastValue = nums.get(nums.size() - 1);
nums.set(index, lastValue);
// 重新維護一下下標的定義
hashMap.put(lastValue, index);
}
// 兩個數據結構都要同時維護
hashMap.remove(val);
nums.remove(nums.size() - 1);
return true;
}
/**
* Get a random element from the set.
*/
public int getRandom() {
return nums.get((int) (Math.random() * nums.size()));
}
}