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();
设计一个数据结构,使得可以在O(1)的时间复杂度中插入数字,删除数字,以及随机获取一个数字。要求全部的数字都可以被等几率的随机出来。java
其实有几个思路入手:数组
这里数字的插入还须要可以去重,即须要首先判断该数字是否已经存在,已经存在的话就不执行任何插入操做。若是底层是一个通常的数组,咱们知道查询的时间复杂度为O(n),明显不知足题目的意思。一个有序的数组可以将查询的时间复杂度降低到O(lgn),可是这依然不知足条件1,并且也没法作到全部的元素被等几率的查询出来,由于每插入一个元素都将改动以前元素的位置。而惟一可以作到O(1)时间查询的只有一个数据结构,即hash。所以,使用hash来查询时不可避免的。数据结构
这个实际上是一个很经典的问题了,只要可以利用hash在O(1)的时间内找到这个数字的位置,就有两种方法来实现O(1)的删除,一个是利用伪删除,即每个位置都对应一个状态为,将状态位社会为已经删除便可,还有一种就更有意思,就是将被删除位替换为数组最后一位的值,而后只须要删除最后一位就行。这种删除就无需将删除位右侧的元素所有左移形成O(n)的时间复杂度。这里咱们采用的是第二种方法。dom
这个其实就是强调一点,咱们须要维持原有的插入顺序,从而保证各个元素等几率被随机。设计
综上所述,咱们底层须要两种数据结构,一个hashmap来支持O(1)的查询,以及一个list来支持随机数的获取。代码实现以下:code
public class InsertDeleteGetRandom_380 { private List<Integer> list; private Map<Integer, Integer> hash; public InsertDeleteGetRandom_380() { list = new ArrayList<Integer>(); hash = new HashMap<Integer, Integer>(); } /** Inserts a value to the set. Returns true if the set did not already contain the specified element. */ public boolean insert(int val) { if(hash.containsKey(val)) { return false; } list.add(val); hash.put(val, list.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(!hash.containsKey(val)){ return false; } int position = hash.get(val); if(position != list.size()-1) { int last = list.get(list.size()-1); list.set(position, last); hash.put(last, position); } list.remove(list.size()-1); hash.remove(val); return true; } /** Get a random element from the set. */ public int getRandom() { int position = (int)Math.floor((Math.random() * list.size())); return list.get(position); } }