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();
Solution:ArrayList + Hashmap(pos)
思路:
(1) insert的話,check map,如果沒有,insert到ArrayList的最后即可。
(2) remove:check map,如果有,找到該位置,swap它和最后一個元素的值,并刪除最后一個元素
(3) getRandom:random index
Time Complexity: O(1) Space Complexity: O(N)
Duplicate allowed:
- Insert Delete GetRandom O(1) - Duplicates allowed
https://leetcode.com/problems/insert-delete-getrandom-o1-duplicates-allowed/
https://leetcode.com/problems/insert-delete-getrandom-o1-duplicates-allowed/discuss/85540/Java-HaspMap-LinkedHashSet-ArrayList-(155-ms)
NOTE:
- 不能 直接用set的通過無序性pop 的原因:set的無序(unordered)并不是真正的隨機,只是指set是已經無序的固定的了。
- 不能 直接用set的然后iterator來找random 的原因:需要用iterator來訪問的,which might cost more than O(n): Iterating over hashset requires time proportional to the sum of the HashSet instance's size (the number of elements) plus the "capacity" of the backing HashMap instance (the number of buckets).
Solution Code:
public class RandomizedSet {
ArrayList<Integer> nums;
HashMap<Integer, Integer> locs;
java.util.Random rand;
/** Initialize your data structure here. */
public RandomizedSet() {
nums = new ArrayList<Integer>();
locs = new HashMap<Integer, Integer>();
rand = new java.util.Random();
}
/** Inserts a value to the set. Returns true if the set did not already contain the specified element. */
public boolean insert(int val) {
if (locs.containsKey(val)) return false;
locs.put(val, nums.size());
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 (!locs.containsKey(val)) return false;
int loc = locs.get(val);
// not the last one, then swap the last one with this val
if (loc < nums.size() - 1) {
int lastone = nums.get(nums.size() - 1);
nums.set(loc ,lastone);
locs.put(lastone, loc);
}
locs.remove(val);
nums.remove(nums.size() - 1);
return true;
}
/** Get a random element from the set. */
public int getRandom() {
return nums.get(rand.nextInt(nums.size()));
}
}