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

数据结构设计问题,从网上找的参考答案。

根据以上的思路,写了一份python版本的代码:

 class RandomizedSet:
def __init__(self):
"""
Initialize your data structure here.
"""
self.dic = dict()
self.l = list()
self.length = def insert(self, val: int) -> bool:
"""
Inserts a value to the set. Returns true if the set did not already contain the specified element.
"""
if val in self.dic:
return False
else:
self.dic[val] = self.length
self.l.append(val)
self.length +=
return True def remove(self, val: int) -> bool:
"""
Removes a value from the set. Returns true if the set contained the specified element.
"""
if val not in self.dic:
return False
else:
self.dic.pop(val)
self.l.remove(val)
self.length -=
return True def getRandom(self) -> int:
"""
Get a random element from the set.
"""
rnd = int(random.uniform(, self.length))
key = self.l[rnd]
return key

leetcode380的更多相关文章

  1. LeetCode380 常数时间插入、删除和获取随机元素

    LeetCode380 常数时间插入.删除和获取随机元素 题目要求 设计一个支持在平均 时间复杂度 O(1) 下,执行以下操作的数据结构. insert(val):当元素 val 不存在时,向集合中插 ...

  2. [Swift]LeetCode380. 常数时间插入、删除和获取随机元素 | Insert Delete GetRandom O(1)

    Design a data structure that supports all following operations in averageO(1) time. insert(val): Ins ...

  3. 2017-3-8 leetcode 380 381 532

    l两周以来,第一次睡了个爽,开心! ================================= leetcode380 https://leetcode.com/problems/insert ...

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

随机推荐

  1. BZOJ4565 [Haoi2016]字符合并

    题意 有一个长度为\(n\)的\(01\)串,你可以每次将相邻的\(k\)个字符合并,得到一个新的字符并获得一定分数.得到的新字符和分数由这\(k\)个字符确定.你需要求出你能获得的最大分数. \(n ...

  2. matplotlib ----- 初步

    直接看几段代码即可: # 加载模块的方式 import matplotlib.pyplot as plt import numpy as np # 最简单的单线图 x = np.linspace(0, ...

  3. 什么是虚拟环境、为什么使用虚拟环境、Anaconda创建、激活、退出、删除虚拟环境

    一.虚拟环境 virtual environment 它是一个虚拟化,从电脑独立开辟出来的环境.通俗的来讲,虚拟环境就是借助虚拟机docker来把一部分内容独立出来,我们把这部分独立出来的东西称作“容 ...

  4. centos7下安装oracle11gR2

    Centos7安装oracle11gR2说明 Centos7安装oracle11gR2说明 环境准备 安装Oracle前准备 创建运行oracle数据库的系统用户和用户组 创建oracle数据库安装目 ...

  5. np.random的随机数函数

    np.random的随机数函数(1) 函数 说明 rand(d0,d1,..,dn) 根据d0‐dn创建随机数数组,浮点数, [0,1),均匀分布 randn(d0,d1,..,dn) 根据d0‐dn ...

  6. centos6 查看SELinux状态 关闭SELinux

    SELinux(Security-Enhanced Linux) 是美国国家安全局(NSA)对于强制访问控制的实现,是 Linux历史上最杰出的新安全子系统.在这种访问控制体系的限制下,进程只能访问那 ...

  7. mysql binlog_format row and Statement 比较

    两种模式的对比: Statement 优点 历史悠久,技术成熟: 产生的 binlog 文件较小: binlog 中包含了所有数据库修改信息,可以据此来审核数据库的安全等情况: binlog 可以用于 ...

  8. Unit07: 状态管理-Session

    Unit07: 状态管理-Session web package web; import java.io.IOException; import java.io.PrintWriter; import ...

  9. 关于vim搜索/替换功能的两条配置

    之前是直接照着这篇的配置的强大的vim配置文件 自己也只是对vim新建文件修改文件的哪个函数SetTitle()做了点修改,毕竟用vim只写C/C++和python.shell. 没想到今天在用vim ...

  10. vim 编辑技巧

    vi是linux下最常用的编辑器,vim是vi的加强版,本篇将介绍vim的一些快捷键和使用技巧,借鉴网上其他文章表示