380. Insert Delete GetRandom O(1)
Difficulty: Medium
Related Topics: Array, Hash Table, Design
Implement the RandomizedSet class:
bool insert(int val)Inserts an itemvalinto the set if not present. Returnstrueif the item was not present,falseotherwise.bool remove(int val)Removes an itemvalfrom the set if present. Returnstrueif the item was present,falseotherwise.int getRandom()Returns a random element from the current set of elements (it’s guaranteed that at least one element exists when this method is called). Each element must have the same probability of being returned.
Follow up: Could you implement the functions of the class with each function works in average O(1) time?
Example 1:
Input
["RandomizedSet", "insert", "remove", "insert", "getRandom", "remove", "insert", "getRandom"]
[[], [1], [2], [2], [], [1], [2], []]
Output
[null, true, false, true, 2, true, false, 2]
Explanation
RandomizedSet randomizedSet = new RandomizedSet();
randomizedSet.insert(1); // Inserts 1 to the set. Returns true as 1 was inserted successfully.
randomizedSet.remove(2); // Returns false as 2 does not exist in the set.
randomizedSet.insert(2); // Inserts 2 to the set, returns true. Set now contains [1,2].
randomizedSet.getRandom(); // getRandom() should return either 1 or 2 randomly.
randomizedSet.remove(1); // Removes 1 from the set, returns true. Set now contains [2].
randomizedSet.insert(2); // 2 was already in the set, so return false.
randomizedSet.getRandom(); // Since 2 is the only number in the set, getRandom() will always return 2.
Constraints:
-2<sup>31</sup> <= val <= 2<sup>31</sup> - 1- At most
10<sup>5</sup>calls will be made toinsert,remove, andgetRandom. - There will be at least one element in the data structure when
getRandomis called.
Solution
Key: When achiving good time complexity involving data structures, make good use of both hashmap and arrrayLists
Language: Java
class RandomizedSet {
HashMap<Integer, Integer> store = new HashMap<>();
ArrayList<Integer> indices = new ArrayList<>();
Random random;
/** Initialize your data structure here. */
public RandomizedSet() {
this.random = new Random();
// this.indices.add(1);
}
/** Inserts a value to the set. Returns true if the set did not already contain the specified element. */
public boolean insert(int val) {
boolean isExist = store.containsKey(val);
if (!isExist) {
indices.add(val);
store.put(val, indices.size() - 1);
}
return !isExist;
}
/** Removes a value from the set. Returns true if the set contained the specified element. */
public boolean remove(int val) {
boolean isExist = store.containsKey(val);
if (isExist) {
int index = store.get(val);
int toMoveIndex = indices.size() - 1;
int toMove = indices.get((int) toMoveIndex);
indices.set(index, toMove);
store.put(toMove, index);
indices.remove((int) toMoveIndex);
store.remove(val);
}
return isExist;
}
/** Get a random element from the set. */
public int getRandom() {
int ran = this.random.nextInt(this.indices.size());
return indices.get(ran);
}
}
/**
* Your RandomizedSet object will be instantiated and called as such:
* RandomizedSet obj = new RandomizedSet();
* boolean param_1 = obj.insert(val);
* boolean param_2 = obj.remove(val);
* int param_3 = obj.getRandom();
*/
随机集合实现

本文介绍了一个支持插入、删除和随机返回元素的随机集合类的实现。该集合确保每个操作的平均时间复杂度为O(1),并使用哈希表和数组结合的方式达到此目标。
795

被折叠的 条评论
为什么被折叠?



