Insert Delete GetRandom O(1)
题目链接:Insert Delete GetRandom O(1)
思路:
- 本题和JAVA中的set集合中的插入删除极为相似,所以最简便的方法是使用set集合进行模拟,插入删除不用修改,在返回随机数时,由于set集合不能够返回指定位置的值,所以要对其进行转换,可以将set集合转换为ArrayList,然后再返回随机位置的值。
- 这种方法的缺点是运行时间太长,主要是消耗在set集合转化为list集合返回随机数时。提交仅击败7%
- 第二种方法是:定义一个Map和一个List,map的key存储插入的值,value存储插入的顺序,List存储插入的数据,目的是删除时,能让map和下标之间重新建立正确的映射,因为我们后面取随机数时需要用到下标,所以下标不应该产生跳跃,最绕人的就是删除,插入都是按顺序插入,没有好解释的,删除时:首先需要O(1)复杂度,所以不能遍历list,就需要先将最后一个值覆盖待删除的值,然后只删除最后一个值即可,由于位置调换,所以map中的对应key值的val也需要更新,代码如下。
解法一:
public class RandomizedSet{
Set<Integer> set = null;
/** Initialize your data structure here. */
public RandomizedSet() {
set = new HashSet<Integer>();
}
/** Inserts a value to the set. Returns true if the set did not already contain the specified element. */
public boolean insert(int val) {
return set.add(val);
}
/** Removes a value from the set. Returns true if the set contained the specified element. */
public boolean remove(int val) {
return set.remove(val);
}
/** Get a random element from the set. */
public int getRandom() {
int length = set.size();
List <Integer> list = new ArrayList<Integer>(set);
return list.get((int) (Math.random()*length));
}
}
解法二:
public class RandomizedSet{
Map<Integer,Integer> map = null;
List<Integer> list = null;
int size = 0;
/** Initialize your data structure here. */
public RandomizedSet() {
map = new HashMap<Integer,Integer>();
list = new ArrayList<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(map.containsKey(val)) {
return false;
}else {
list.add(size,val);
map.put(val, size++);
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;
}else {
int index = map.get(val);
list.set(index,list.get(size-1));
map.put(list.get(index),index);
size--;
map.remove(val);
}
return true;
}
public int getRandom() {
// System.out.println(list.size());
return list.get((int) (Math.random()*size));
}
}