Leetcode 380. 常数时间插入、删除和获取随机元素
1.题目描述
设计一个支持在平均 时间复杂度 O(1) 下,执行以下操作的数据结构。
insert(val):当元素 val 不存在时,向集合中插入该项。remove(val):元素 val 存在时,从集合中移除该项。getRandom:随机返回现有集合中的一项。每个元素应该有相同的概率被返回
示例:
// 初始化一个空的集合。
RandomizedSet randomSet = new RandomizedSet(); // 向集合中插入 1 。返回 true 表示 1 被成功地插入。
randomSet.insert(); // 返回 false ,表示集合中不存在 2 。
randomSet.remove(); // 向集合中插入 2 。返回 true 。集合现在包含 [1,2] 。
randomSet.insert(); // getRandom 应随机返回 1 或 2 。
randomSet.getRandom(); // 从集合中移除 1 ,返回 true 。集合现在包含 [2] 。
randomSet.remove(); // 2 已在集合中,所以返回 false 。
randomSet.insert(); // 由于 2 是集合中唯一的数字,getRandom 总是返回 2 。
randomSet.getRandom();
2.解题思路
分析:题目的难点在于有delete操作的情况下,要保证getRandom( )等概率随机返回集合中的一个元素。
一般地,题目的对时间复杂度的要求越高,都需要使用更多的辅助结构,以“空间换时间”。这里可以采用“两个哈希表”(多一个哈希表)或者“一个哈希表加一个数组”(多一个数组)。
渐进思路:
(1)没有delete(val),只有insert(val)和getRandom( )操作的情况下,连续的插入元素键值对<key,index>,因为index在逻辑上是连续,因此getRandom()等概率随机返回集合中的一个元素很容易实现,rand() % index (0~index-1)即可;
(2)有delete(val)操作,可以删除元素键值对之后,使得index不连续,中间有空洞,所以此时getRandom()产生的index可能正好是被删除的,导致时间复杂度超过O(1),所以delete(val)操作需要有一些限定条件,即保证每删除一个元素键值对之后,index个数减一,但是整体index在逻辑上是连续的。
例如:0~5 ——> 0~4 ——> 0~3
代码里关键部分有注释。
class RandomizedSet {
public:
/** Initialize your data structure here. */
//建立两个hash表,一个是<key,index>,另一个是<index,key>;
RandomizedSet() {
}
/** Inserts a value to the set. Returns true if the set did not already contain the specified element. */
bool insert(int val) {
//元素不存在时,插入
if(keyIndexMap.count(val) == )
{
keyIndexMap[val] = size;
indexKeyMap[size] = val;
++size;
return true;
}
return false;
}
/** Removes a value from the set. Returns true if the set contained the specified element. */
bool remove(int val) {
////每删除一个键值对,用最后的键值对填充该空位,保证整个index在逻辑上连续,size减一
if(keyIndexMap.count(val) == )
{
int removeIndex = keyIndexMap[val];
int lastIndex = --size;//若size=1000,表示0~999;这里是取最后一个index
int lastKey = indexKeyMap[lastIndex];
keyIndexMap[lastKey] = removeIndex;
indexKeyMap[removeIndex] = lastKey;
keyIndexMap.erase(val);
indexKeyMap.erase(lastIndex);//下标方式取val对应的值index
return true;
}
return false;
}
/** Get a random element from the set. */
int getRandom() {
if (size == ) {
return NULL;
}
//srand((unsigned)time(NULL)); //去掉srand(),保证稳定的产生随机序列
int randomIndex = (int) (rand() % size); // 0 ~ size -1
return indexKeyMap[randomIndex];
}
private:
map<int,int> keyIndexMap;
map<int,int> indexKeyMap;
int size = ;
};
/**
* Your RandomizedSet object will be instantiated and called as such:
* RandomizedSet obj = new RandomizedSet();
* bool param_1 = obj.insert(val);
* bool param_2 = obj.remove(val);
* int param_3 = obj.getRandom();
*/
3.用时更少的范例
这是Leetcode官网上C++完成此题提高的用时排名靠前的代码,这里与上面的解法差异就在于额外的辅助结构的选择,这里选的是在哈希表的基础上多增加一个数组,数组操作的时间复杂度和哈希表操作的时间复杂度均为O(1),但是数组时间复杂度O(1)的常数项更小,因此,这种解法效率更高。
class RandomizedSet {
public:
/** Initialize your data structure here. */
RandomizedSet() {
}
/** Inserts a value to the set. Returns true if the set did not already contain the specified element. */
bool insert(int val) {
if (m.count(val)) return false;
nums.push_back(val);
m[val] = nums.size() - ;
return true;
}
/** Removes a value from the set. Returns true if the set contained the specified element. */
bool remove(int val) {
if (!m.count(val)) return false;
int last = nums.back();
m[last] = m[val];
nums[m[val]] = last;
nums.pop_back();
m.erase(val);
return true;
}
/** Get a random element from the set. */
int getRandom() {
return nums[rand() % nums.size()];
}
//private:
//注释掉private,提高一点速度
vector<int> nums;
unordered_map<int, int> m;
};
/**
* Your RandomizedSet object will be instantiated and called as such:
* RandomizedSet obj = new RandomizedSet();
* bool param_1 = obj.insert(val);
* bool param_2 = obj.remove(val);
* int param_3 = obj.getRandom();
*/
Leetcode 380. 常数时间插入、删除和获取随机元素的更多相关文章
- Java实现 LeetCode 380 常数时间插入、删除和获取随机元素
380. 常数时间插入.删除和获取随机元素 设计一个支持在平均 时间复杂度 O(1) 下,执行以下操作的数据结构. insert(val):当元素 val 不存在时,向集合中插入该项. remove( ...
- LeetCode 381. Insert Delete GetRandom O(1) - Duplicates allowed O(1) 时间插入、删除和获取随机元素 - 允许重复(C++/Java)
题目: Design a data structure that supports all following operations in averageO(1) time. Note: Duplic ...
- LeetCode380 常数时间插入、删除和获取随机元素
LeetCode380 常数时间插入.删除和获取随机元素 题目要求 设计一个支持在平均 时间复杂度 O(1) 下,执行以下操作的数据结构. insert(val):当元素 val 不存在时,向集合中插 ...
- Java实现 LeetCode 381 O(1) 时间插入、删除和获取随机元素 - 允许重复
381. O(1) 时间插入.删除和获取随机元素 - 允许重复 设计一个支持在平均 时间复杂度 O(1) 下, 执行以下操作的数据结构. 注意: 允许出现重复元素. insert(val):向集合中插 ...
- 381. O(1) 时间插入、删除和获取随机元素 - 允许重复
381. O(1) 时间插入.删除和获取随机元素 - 允许重复 LeetCode_381 题目详情 题解分析 代码实现 package com.walegarrett.interview; impor ...
- Leetcode 381. O(1) 时间插入、删除和获取随机元素 - 允许重复
1.题目描述 设计一个支持在平均 时间复杂度 O(1) 下, 执行以下操作的数据结构. 注意: 允许出现重复元素. insert(val):向集合中插入元素 val. remove(val):当 va ...
- LeetCode 380. Insert Delete GetRandom O(1) 常数时间插入、删除和获取随机元素(C++/Java)
题目: Design a data structure that supports all following operations in averageO(1) time. insert(val): ...
- LeetCode 哈希表 380. 常数时间插入、删除和获取随机元素(设计数据结构 List HashMap底层 时间复杂度)
比起之前那些问计数哈希表的题目,这道题好像更接近哈希表的底层机制. java中hashmap的实现是通过List<Node>,即链表的list,如果链表过长则换为红黑树,如果容量不足(装填 ...
- 381 Insert Delete GetRandom O(1) - Duplicates allowed O(1) 时间插入、删除和获取随机元素 - 允许重复
设计一个支持在平均 时间复杂度 O(1) 下, 执行以下操作的数据结构.注意: 允许出现重复元素. insert(val):向集合中插入元素 val. remove(val):当 val ...
随机推荐
- FPGA学习-VGA接口
一般FPGA开发板的VGA会向用户暴露两共五个种接口,第一种是时序信号,用于同步传输和显示:第二种是色彩信号,用于随着时序把色彩显示到显示器上 时序接口 行同步信号-用于指示一行内像素的显示 场同步信 ...
- Apache--Override参数详解
1 AuthConfig 允许使用所有的权限指令,他们包括AuthDBMGroupFile AuthDBMUserFile AuthGroupFile AuthName AuthTypeAut ...
- Thunder团队Beta周贡献分分配结果
小组名称:Thunder 项目名称:爱阅app 组长:王航 成员:李传康.翟宇豪.邹双黛.苗威.宋雨.胡佑蓉.杨梓瑞 分配规则 规则1:基础分,拿出总分的20%(8分)进行均分,剩下的80%(32分) ...
- aria2 on ubuntu
http://www.5yun.org/9102.html http://jpollo.logdown.com/posts/160847-aria2c-and-yaaw aria2c --enable ...
- Where to go from here
Did you get through all of that content? Congratulations! You've learnt the fundamentals of algorith ...
- lintcode-33-N皇后问题
33-N皇后问题 n皇后问题是将n个皇后放置在n*n的棋盘上,皇后彼此之间不能相互攻击. 给定一个整数n,返回所有不同的n皇后问题的解决方案. 每个解决方案包含一个明确的n皇后放置布局,其中" ...
- iOS开发给UIView添加动画Animation
self.testView需要添加动画的view 1.翻转动画 [UIView beginAnimations:@"doflip" context:nil]; [UIView se ...
- <Effective C++>读书摘要--Designs and Declarations<三>
<Item 22> Declare data members private 1.使数据成员private,保持了语法的一致性,client不会为访问一个数据成员是否需要使用括号进行函数调 ...
- Css入门课程 Css基础
html css javascript三者关系 html是网页内容的载体 css是网页内容的表现,外观控制 javascript是网页逻辑处理和行为控制 css相对于html标签属性的优势 css简化 ...
- Zabbix监控配置
Zabbix在线文档 https://www.zabbix.com/documentation/4.0/zh/manual/config/hosts 1.我们启动服务后,我们看到了端口都正在监听,但是 ...