380. Insert Delete GetRandom O(1)

实现插入、删除、获得随机数功能,且时间复杂度都在O(1)。实际上在插入、删除两个功能中都包含了查找功能,当然查找也必须是O(1)。

数组可以实现插入、删除、获得随机数O(1),但查找就不行了。(当然对于数组,直接删除的时间复杂度不是O(1),因为可能需要移动)

hash、set都是红黑树实现的,查找、插入、删除的时间复杂度在O(logn)。

unordered_map、unordered_set是哈希表实现的,查找、插入、删除的时间复杂度在O(1)。但unordered_map、unordered_set都只能用迭代器访问,无法用索引访问,所以获得随机数的时间复杂度不是O(1)。但是unordered_map、unordered_set都还是有size()的函数,只是不像vector那样用size来获得index访问。

unordered_set用迭代器访问的方式如下:

#include <iostream>
#include <unordered_set> using namespace std; int main(){
unordered_set<int> s;
s.insert();
s.insert();
s.insert();
for(auto it = s.begin();it != s.end();it++)
cout << *it << endl;
}

注意:result.back()返回的是最后一个位置的数值,不是下标

      在删除的函数中,除了删除vector中存储的数值,还要删除map中数值与索引,不然下次访问还会有这个被删除的数字

vector存储数,unordered_map存储数和对应在vector的下标

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.find(val) != m.end())
return false;
result.push_back(val);
m[val] = result.size() - ;
return true;
} /** Removes a value from the set. Returns true if the set contained the specified element. */
bool remove(int val) {
if(m.find(val) == m.end())
return false;
int index = m[val];
result[index] = result.back();
m[result.back()] = index;
result.pop_back();
m.erase(val);
return true;
} /** Get a random element from the set. */
int getRandom() {
int index = rand() % result.size();
return result[index];
}
private:
vector<int> result;
unordered_map<int,int> m;
};

381. Insert Delete GetRandom O(1) - Duplicates allowed

与380题不同,这个题允许重复

unordered_map存储的数和数对应存储索引的集合,用set存储

class RandomizedCollection {
public:
/** Initialize your data structure here. */
RandomizedCollection() { } /** Inserts a value to the collection. Returns true if the collection did not already contain the specified element. */
bool insert(int val) {
int index = result.size();
result.push_back(val);
m[val].insert(index);
return m[val].size() == ;
} /** Removes a value from the collection. Returns true if the collection contained the specified element. */
bool remove(int val) {
if(m[val].empty())
return false;
int index = *m[val].begin();
m[val].erase(index);
if(index != result.size() - ){
result[index] = result.back();
m[result.back()].erase(result.size() - );
m[result.back()].insert(index);
}
result.pop_back();
return true;
} /** Get a random element from the collection. */
int getRandom() {
if(result.empty())
return -;
int index = rand()%result.size();
return result[index];
}
private:
vector<int> result;
unordered_map<int,set<int>> m;
}; /**
* Your RandomizedCollection object will be instantiated and called as such:
* RandomizedCollection* obj = new RandomizedCollection();
* bool param_1 = obj->insert(val);
* bool param_2 = obj->remove(val);
* int param_3 = obj->getRandom();
*/

leetcode 380. Insert Delete GetRandom O(1) 、381. Insert Delete GetRandom O(1) - Duplicates allowed的更多相关文章

  1. 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 ...

  2. [LeetCode] 380. Insert Delete GetRandom O(1) 常数时间内插入删除和获得随机数

    Design a data structure that supports all following operations in average O(1) time. insert(val): In ...

  3. [LeetCode] 380. Insert Delete GetRandom O(1) 插入删除获得随机数O(1)时间

    Design a data structure that supports all following operations in average O(1) time. insert(val): In ...

  4. [leetcode]380. Insert Delete GetRandom O(1)常数时间插入删除取随机值

    Design a data structure that supports all following operations in average O(1) time. insert(val): In ...

  5. [LeetCode] 381. Insert Delete GetRandom O(1) - Duplicates allowed 插入删除和获得随机数O(1)时间 - 允许重复

    Design a data structure that supports all following operations in average O(1) time. Note: Duplicate ...

  6. Leetcode 380. 常数时间插入、删除和获取随机元素

    1.题目描述 设计一个支持在平均 时间复杂度 O(1) 下,执行以下操作的数据结构. insert(val):当元素 val 不存在时,向集合中插入该项. remove(val):元素 val 存在时 ...

  7. ListView控件的Insert、Edit和Delete功能(第二部分)

    本系列文章将通过一个简单的实例,结合我自己使用ListView的情况,展示如何用ASP.NET 3.5 ListView控件进行基本的Insert.Edit和Delete操作. 系统要求: Windo ...

  8. ListView控件的Insert、Edit和Delete功能(第一部分)

    摘自:http://blog.ashchan.com/archive/2007/08/28/listview-control-insert-edit-amp-delete-part-1aspx/ Li ...

  9. 关于mysql的update、delete、和insert into能否使用别名问题

    在工作中遇到这样一个问题,就是mysql在insert into时能不能使用别名,大家会很奇怪为什么insert into使用别名呢?原因在于原来的项目中使用了user表,新项目要将user表拆分为u ...

随机推荐

  1. 宁波市第二届CTF部分WP之msc1,msc2

    msc1签到 这题没啥好说的,修改一下图片宽高,flag到手 msc2 一开始用十六进制编辑器打开,分析文件,暂时无果,卡了一小时(线下没网) 后面,看着这部分文件头眼熟,猜测是GIF头, 于是,在硬 ...

  2. 高并发下redis

    1.================================================================================================== ...

  3. 【转】Guava cache使用总结

    缓存分为本地缓存和远端缓存.常见的远端缓存有Redis,MongoDB:本地缓存一般使用map的方式保存在本地内存中.一般我们在业务中操作缓存,都会操作缓存和数据源两部分.如:put数据时,先插入DB ...

  4. Linux中rpm命令用法

    rpm -ivh 软件包名 安装软件包并显示安装进度.这个是用得最多的了. rpm -qa 查询已经安装哪些软件包. rpm -q 软件包名 查询指定软件包是否已经安装. rpm -Uvh  软件包名 ...

  5. 机械师实时调度示例(I) - 实时规划

    OptaPlanner创办人Geoffrey De Smet及其团队,在Red Hat 技术峰会上主题会场上,演示了一个通过OptaPlanner实现实时规划与调度的示例.Geoffrey及其团队专门 ...

  6. 布隆过滤器(Bloom Filter)-学习笔记-Java版代码(挖坑ing)

    布隆过滤器解决"面试题: 如何建立一个十亿级别的哈希表,限制内存空间" "如何快速查询一个10亿大小的集合中的元素是否存在" 如题 布隆过滤器确实很神奇, 简单 ...

  7. javax.servlet.ServletException: Circular view path [index]: would dispatch back to the current handler URL [/pay/index] again. Check your ViewResolver setup!

    2019-08-08 17:12:03.544 ERROR 13748 --- [nio-8080-exec-2] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Se ...

  8. MySQL 查询排除指定字段、自定义变量、动态执行SQL

    今天在项目中,要查询一个表.这个表中有几十个字段.但是要把其中的一个特殊处理. 这个该怎么办呢?查来查去,SQL 中没有排除某一些字段的语句,只能单独写一些语句来处理: 基本思路:对于MySQL数据库 ...

  9. 《BUG创造队》作业8:软件测试与Alpha冲刺(第二天)

    项目 内容 这个作业属于哪个课程 2016级软件工程 这个作业的要求在哪里 实验十二 团队作业8:软件测试与ALPHA冲刺 团队名称 BUG创造队 作业学习目标 (1)掌握软件测试基础技术.(2)学习 ...

  10. SVM:从数学上分析为什么优化cost function会产生大距离(margin)分类器

    向量内积 uTv = vTu为两个二维向量的内积,它等于p*||u||(其中p为向量v在向量u上的投影长度,是有+/-之分的,||u||为向量u的长度也称为范数),它是一个实数(是一个标量). 如上图 ...