实现RandomizedSet类:
(1)RandomizedSet() 初始化RandomizedSet对象。
(2)bool insert(int val) 当元素val 不存在时,集合中插入该项,并返回true ;否则,返回false 。
(3)bool remove(int val) 当元素val存在时,从集合中移除该项,并返回true ;返迥false。
(4)int getRandom()随机返回现有集合中的一项。每个元素应该有相同的概率被返回。
实现类的所有函数,并满足每个函数的平均时间复杂度为0(1) 。
class RandomizedSet {
List<Integer> list;
Map<Integer,Integer> map;
Random random;
public RandomizedSet() {
list = new ArrayList<>();
map = new HashMap<>();
random = new Random();
}
public boolean insert(int val) {
if(map.containsKey(val)){
return false;
}
list.add(val);
map.put(val,list.size());
return true;
}
public boolean remove(int val) {
if(!map.containsKey(val)){
return false;
}
int index = map.get(val);
int last = list.get(list.size()-1);
list.set(index,last);
map.put(last,index);
list.remove(list.size()-1);
map.remove(val);
return true;
}
public int getRandom() {
int randomIndex = random.nextInt(list.size());
return list.get(randomIndex);
}
}