Question
Formatted question description: https://leetcode.ca/all/380.html
380 Insert Delete GetRandom O(1)
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();
Follow up:
Could you implement the functions of the class with each function works in average O(1) time?
@tag-array
Algorithm
Use a one-dimensional array
and a HashMap
, where
- the
array
is used to store the numbers, - and the
HashMap
is used to establish the mapping between each number and its position in the array.
For insert()
operation, first check whether this number already exists in HashMap,
- If it exists, return false directly,
- If it does not exist, insert it at the end of the array, and then create a mapping between the number and its position.
The delete()
operation is tricky. It is necessary to determine whether it is in the HashMap first,
- If not, return false directly. Because the deletion of HashMap is constant time, but the array is not, in order to make the deletion of the array also constant level, in fact, the number to be deleted and the last number of the array are exchanged, and then the value in the corresponding HashMap is modified. You only need to delete the last element of the array, which ensures deletion within a constant time.
Returning a random()
number is very simple for an array, as long as a position is randomly generated, the number at that position is returned.
Code
Java
-
public class Insert_Delete_GetRandom_O_1 { public static void main(String[] args) { Insert_Delete_GetRandom_O_1 out = new Insert_Delete_GetRandom_O_1(); // Init an empty set. RandomizedSet randomSet = out.new RandomizedSet(); System.out.println(randomSet.remove(0)); System.out.println(randomSet.remove(0)); System.out.println(randomSet.insert(0)); System.out.println(randomSet.insert(0)); System.out.println(randomSet.insert(0)); System.out.println(randomSet.getRandom()); System.out.println(randomSet.remove(0)); System.out.println(randomSet.insert(0)); } class RandomizedSet { List<Integer> list; Map<Integer, Integer> map; // val => its index in list Random random; /** Initialize your data structure here. */ public RandomizedSet() { list = new ArrayList<>(); map = new HashMap<>(); random = new 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 (map.containsKey(val)) { return false; } int pos = list.size(); list.add(val); map.put(val, pos); 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; } // swap val to end of list, then remove it int pos = map.get(val); int lastVal = list.get(list.size() - 1); list.set(pos, lastVal); list.remove(list.size() - 1); map.put(lastVal, pos); // @note: missed this line map.remove(val); return true; } /** Get a random element from the set. */ public int getRandom() { int randIndex = random.nextInt(list.size()); return list.get(randIndex); } } /** * 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(); */ }
-
// OJ: https://leetcode.com/problems/insert-delete-getrandom-o1/ // Time: O(1) for all // Space: O(N) class RandomizedSet { unordered_map<int, int> m; // value -> index vector<int> v; public: RandomizedSet() {} bool insert(int val) { if (m.count(val)) return false; m[val] = v.size(); v.push_back(val); return true; } bool remove(int val) { if (m.count(val) == 0) return false; if (v.back() != val) { m[v.back()] = m[val]; swap(v[m[val]], v.back()); } v.pop_back(); m.erase(val); return true; } int getRandom() { return v[rand() % v.size()]; } };
-
class RandomizedSet(object): def __init__(self): """ Initialize your data structure here. """ self.d = {} self.a = [] def insert(self, val): """ Inserts a value to the set. Returns true if the set did not already contain the specified element. :type val: int :rtype: bool """ if val in self.d: return False self.a.append(val) self.d[val] = len(self.a) - 1 return True def remove(self, val): """ Removes a value from the set. Returns true if the set contained the specified element. :type val: int :rtype: bool """ if val not in self.d: return False index = self.d[val] self.a[index] = self.a[-1] self.d[self.a[-1]] = index self.a.pop() del self.d[val] return True def getRandom(self): """ Get a random element from the set. :rtype: int """ return self.a[random.randrange(0, len(self.a))] # Your RandomizedSet object will be instantiated and called as such: # obj = RandomizedSet() # param_1 = obj.insert(val) # param_2 = obj.remove(val) # param_3 = obj.getRandom()