算法
(设计+数组+哈希) $O(1)$
工具类的使用。
Java 代码
class RandomizedSet {
// array: vals
List<Integer> nums;
// map: (vals, idx)
Map<Integer, Integer> map;
/** Initialize your data structure here. */
public RandomizedSet() {
nums = new ArrayList();
map = 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 (map.containsKey(val)) return false;
nums.add(val);
map.put(val, nums.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 (!map.containsKey(val)) return false;
int idx = map.get(val);
int n = nums.size();
int temp = nums.get(n - 1);
nums.set(idx, temp);
nums.remove(n - 1);
map.put(temp, idx);
map.remove(val);
return true;
}
/** Get a random element from the set. */
public int getRandom() {
Random rand = new Random();
return nums.get(rand.nextInt(nums.size()));
}
}