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. Linux下安装zookeeper和启动

    原文:https://yq.aliyun.com/articles/662422 1.zookeeper官网下载安装包http://mirrors.hust.edu.cn/apache/zookeep ...

  2. 【OI备忘录】trick汇总帖

    OI中的那些实用的小trick 在OI中,我们时常会用到一些小技巧,无论是代码方面还是数学方面抑或是卡常,都有很多不错的小技巧. 鄙人不才,往往没办法想出来,于是就有了这篇汇总帖~ 如有疏漏,还请da ...

  3. 神经网络(14)--具体实现:put it together

    如何选择神经网络的architecture input units和output units都很好决定,关于hidden layer的层数,则一般来说是选择一个hidden layer, 或者> ...

  4. SSMS开发利器Sql Prompt

    一.前言 一个Sql Server 开发智能提示插件,方便查询表结果,避免了开发人员一个个敲查询语句.执行语句等,一起来看看吧. SQL Prompt 9.5 支持SSMS18 下载地址: 链接:ht ...

  5. Java - 基础到进阶

    # day01 一:基本操作 package _01.java基本操作; /** * 文档注释 */ public class _01Alls { public static void main(St ...

  6. 3种方法实现CSS隐藏滚动条并可以滚动内容

    隐藏滚动条的同时还需要支持滚动,我们经常在前端开发中遇到这种情况,最容易想到的是加一个iscroll插件,但其 实现在CSS也可以实现这个功能,我已经在很多地方使用了,下面一起看看这三种方法. 方法1 ...

  7. 非自增编号字段,避免生成重复编号(以pdfNo编号为例)RedisLock/ReadLock

    非自增编号字段,避免生成重复编号(以pdfNo编号为例) 有个场景,用户查询延误航班信息,然后生产一个编号,默认第一个编号是1000001,其后新增的编号默认自增加1.每次有人来查延误信息,如果延误信 ...

  8. neo4j安装部署

    链接: https://blog.csdn.net/u013946356/article/details/81736232

  9. linux学习7 Linux文件系统功能和作用详解

    一.终端 1.用户界面 GUI: GNome KDE CLI: bash,zsh,sh,csh,tcsh,ksh 2.远程连接 a.ssh协议. 查看系统是否监听于tcp协议的22号端口: ss  - ...

  10. C# 可为空?及(??、?. )

    可空类型修饰符(?): 引用类型可以使用空引用表示一个不存在的值,而值类型通常不能表示为空. 例如:string str=null; 是正确的,int i=null; 编译器就会报错. 为了使值类型也 ...