设计一个支持在平均 时间复杂度 O(1) 下,执行以下操作的数据结构。
insert(val):当元素 val 不存在时,向集合中插入该项。
remove(val):元素 val 存在时,从集合中移除该项。
getRandom:随机返回现有集合中的一项。每个元素应该有相同的概率被返回。输入:["RandomizedSet","insert","remove","insert","getRandom","remove","insert","getRandom"]
[[],[1],[2],[2],[],[1],[2],[]]输出:[null,true,false,true,2,true,false,2]
class RandomizedSet {
Set<Integer> set;
Random random=new Random();
public RandomizedSet() {
set=new HashSet();
}
public boolean insert(int val) {
if(!set.contains(val)){
set.add(val);
return true;
}
return false;
}
public boolean remove(int val) {
if(set.contains(val)){
set.remove(val);
return true;
}
return false;
}
public int getRandom() {
Iterator<Integer> iter=set.iterator();
List<Integer> list=new ArrayList();
while(iter.hasNext()){
list.add(iter.next());
}
return list.get(random.nextInt(list.size()));
}
}
本文介绍了一种使用Java实现的支持insert、remove和getRandom操作的数据结构。该结构能在平均时间复杂度为O(1)的情况下完成操作。具体包括:1) insert(val) 当val不存在时插入;2) remove(val) 当val存在时移除;3) getRandom 随机返回集合中的一个元素。
247

被折叠的 条评论
为什么被折叠?



