657. Insert Delete GetRandom O(1
Description
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.
思路:
开始想只用hash map来解决问题,但是最后一个random的无法实现,set()也是一样,然后答案巧妙的结合了数组和hash_map, 因为数组正常的删除是O(1-n)的复杂度, 当删除的是最后一个的时候就是O(1)的复杂度, 这样可以通过交换要删除的对象和最后一个值实现(其实不需要真正的交换,只要将待删除的值替换成数组末尾值,然后直接删除掉数组末尾就可以)。
使用数组来保存当前集合中的元素,同时用一个hashMap来保存数字与它在数组中下标的对应关系。
插入操作时:
若已存在此元素返回false
不存在时将新的元素插入数组最后一位,同时更新hashMap。
删除操作时:
若不存在此元素返回false
存在时先根据hashMap得到要删除数字的下标,再将数组的最后一个数放到需要删除的数的位置上,删除数组最后一位,同时更新hashMap。
获取随机数操作时:
根据数组的长度来获取一个随机的下标,再根据下标获取元素。
代码:
