原题
设计一个支持在平均 时间复杂度 O(1) 下,执行以下操作的数据结构。
insert(val)
:当元素 val 不存在时,向集合中插入该项。remove(val)
:元素 val 存在时,从集合中移除该项。getRandom
:随机返回现有集合中的一项。每个元素应该有相同的概率被返回。
示例:
// 初始化一个空的集合。
RandomizedSet randomSet = new RandomizedSet();// 向集合中插入 1 。返回 true 表示 1 被成功地插入。
randomSet.insert(1);// 返回 false ,表示集合中不存在 2 。
randomSet.remove(2);// 向集合中插入 2 。返回 true 。集合现在包含 [1,2] 。
randomSet.insert(2);// getRandom 应随机返回 1 或 2 。
randomSet.getRandom();// 从集合中移除 1 ,返回 true 。集合现在包含 [2] 。
randomSet.remove(1);// 2 已在集合中,所以返回 false 。
randomSet.insert(2);// 由于 2 是集合中唯一的数字,getRandom 总是返回 2 。
randomSet.getRandom();
解法
思想
- 初始想法
哈希表的插入删除的时间复杂度都是O(1)
,获取的时候可以通过EntrySet。
所以这道题是不能用HashSet的。
这样虽然获取随机元素的时候时间复杂度最高可能是O(n)
,但仍比遍历一遍Set转ArrayList好很多。
- 正确解法
哈希表插入和删除都是O(1)
,而顺序表随机访问则是O(1)
,可以使用ArrayList来存储所有的数据。但是必须解决ArrayList删除元素的O(n)
问题。
于是可以:
在哈希表中用value-index来记录值和在list中的下标的对应关系,如图所示

当删除元素时,size减一,用list中最后那个元素替换要删除的那个元素,并且将哈希表中的对应关系改过来(用要删除的元素的index替换list中最后那个元素对应的index):

此时若要随机访问元素,只需获取list中前3(size)个元素中的一个。
那么如果需要继续插入元素,只需从list中下标为3(size)处替换掉后面那个元素或是在后面那个元素之前插入(这里如果用插入是使用add(index,value)方法,个人觉得比起set会增加时间复杂度,因为使用add后面的元素都需要向后移动,虽然jdk源码中使用了System.arraycopy即内存拷贝来优化,但是也比直接替换的时间复杂度更高):

如果不是替换元素而是add操作,这里会变成1-4-2-8-4
。
代码
- 初始想法
class RandomizedSet {
Object none = new Object();
HashMap<Integer,Object> map;
Random random;
/** Initialize your data structure here. */
public RandomizedSet() {
map = new HashMap<>();
random = new Random();
}
/** 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;
map.put(val,none);
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;
map.remove(val);
return true;
}
/** Get a random element from the set. */
public int getRandom() {
int ran = random.nextInt(map.size());
int n = 0;
for(Map.Entry<Integer,Object> i:map.entrySet()){
if(n==ran) return i.getKey();
n++;
}
return 0;
}
}
/**
* Your RandomizedSet object will be instantiated and called as such:
* RandomizedSet obj = new RandomizedSet();
* boolean param_1 = obj.insert(val);
* boolean param_2 = obj.remove(val);
* int param_3 = obj.getRandom();
*/
- 正确解法(来源:leetcode用户,添加元素时是直接插入)
class RandomizedSet {
Map<Integer,Integer> map; // 存放值和在 list 的下标位置的映射
List<Integer> list; // 存放要插入数据的结构
int size; // 数据的长度
/** Initialize your data structure here. */
public RandomizedSet() {
map = new HashMap<>();
list = new ArrayList<>();
size = 0;
}
/** 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{
// 插入数据,并更新 map 的映射后将长度加一
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 if( size == 0 ){ map.remove(val);}
else{
// 取到 list 末尾的数据
int tailKey = list.get(size-1);
// 然后将要原先 map 中得 val-index 映射改为 tailKey-index
map.put(tailKey,map.get(val));
// 在 map 中取得 val 在 list 的位置,然后根据这个位置用末尾元素 tailKey 替代
list.set(map.get(val),tailKey);
// 在 map 中删除 val 的映射
map.remove(val);
size--;
}
return true;
}
/** Get a random element from the set. */
public int getRandom() {
Random rand = new Random();
// rand.nextInt(size) 产生的是 0 到 size(不包括 size) 的数据
return list.get(rand.nextInt(size));
}
}
原创文章,作者:彭晨涛,如若转载,请注明出处:https://www.codetool.top/article/leetcode380-%e5%b8%b8%e6%95%b0%e6%97%b6%e9%97%b4%e6%8f%92%e5%85%a5%e3%80%81%e5%88%a0%e9%99%a4%e5%92%8c%e8%8e%b7%e5%8f%96%e9%9a%8f%e6%9c%ba%e5%85%83%e7%b4%a0/