问题:
How would you define a data structure that stores a set ofvalues (i.e., a value cannot appear more than one time), and implements the following functions:
add(p)--adds the value p to the setdelete(p)--removes the value p from the set
getrandom()--returns a random value from the set (all items should be equally likely). (Assume you have access to some nice random()function.)
All operations should be O(1) time complexity.
这个题目是要求实现一个Set,但是在add/delete操作之外,还需要O(1)的时间返回一个随机元素。矛盾的地方是,Set可以很容易达到add/deleteO(1), 但是O(1)返回随机元素是数组的性质。这是两种截然不同的数据结构。
Set: add/delete O(1), getrandom O(n)
Array: add O(1), delete O(n), getrandom O(1)
那么解决方案就是把两种数据结构结合在一起共同达到三种操作O(1)复杂度。其中最主要的任务在于如何使得Array的delete操作达到O(1)。代码如下,这个trick一看便知。
class RandomSet
{
HashMap<Integer,Integer> hm=new HashMap<Integer,Integer>();
ArrayList<Integer> al=new ArrayList<Integer>();
void add(Integer num)
{
if(!hm.containsKey(num))
{
al.add(num);
hm.put(num, al.size()-1);
}
}
void delete(Integer num)
{
if(hm.containsKey(num))
{
if(hm.get(num)<al.size()-1)
{
int last=al.get(al.size()-1);
al.set(hm.get(num), last);
hm.put(last,hm.get(num));
}
al.remove(al.size()-1);
hm.remove(num);
}
}
Integer getrandom()
{
if(al.size()==0)
return null;
return al.get(new Random().nextInt(al.size()));
}
}转自:http://blog.sina.com.cn/s/blog_b9285de20101gx01.html
本文介绍了一种特殊的数据结构——随机Set,它不仅能在O(1)时间内完成添加和删除操作,还能在O(1)时间内返回集合中的随机元素。通过结合使用HashMap和ArrayList,实现了所有操作的高效执行。

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



