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. 【剑指offer】不用加减乘除做加法,C++实现

    原创博文,转载请注明出处! # 题目 # 思路 第一步:不考虑进位对每一位相加(异或操作) 第二步:考虑进位(位与运算+左移) 第三步:第一步和第二步相加(重复执行前两步) # 代码 #include ...

  2. baos bais 意义

    import java.io.BufferedInputStream; import java.io.ByteArrayInputStream; import java.io.ByteArrayOut ...

  3. 【javascript】如何延迟加载JavaScript(Google推荐的代码)

    下面是Google推荐的代码.这些代码应被放置在</body>标签前(接近HTML文件底部)<script type="text/javascript">f ...

  4. js生成guid(唯一标识码)

    在使用postman对接口进行测试的时候,有时候接口日志会要求写入随机标识码,这里我们可以使用js来生成. // Generate four random hex digits. function S ...

  5. HDU3853LOOPS (师傅逃亡系列•三)(基础概率DP)

    Akemi Homura is a Mahou Shoujo (Puella Magi/Magical Girl). Homura wants to help her friend Madoka sa ...

  6. Associations marked as mappedBy must not define database mappings like @JoinTable or @JoinColumn【报错】

    自己的项目没有测通  可能是自己项目原因——因为自己项目中级联关系的类涉及太多 自己的项目[这样的配置报错] @OneToMany(fetch=FetchType.LAZY,cascade = { C ...

  7. HTML5移动Web开发指南-学习笔记(一)

    一,浏览器引擎    浏览器的内核引擎,基本上是四分天下: Trident: IE 以Trident 作为内核引擎; Gecko: Firefox 是基于 Gecko 开发; WebKit: Safa ...

  8. SqlServer使用CONVERT 对时间进行格式化

    前言 在最近使用SqlServer的时候遇到时间格式的转换,特此记录下. 本文参考:https://www.cnblogs.com/xiaoleiel/p/8301027.html,如有侵权,请联系删 ...

  9. c++调用fortran程序中遇到的问题

    一.C++动态调用Fortran DLL (1)创建FORTRAN DLL工程,生成forsubs.dll文件供调用. ! forsubs.f90 ! ! FUNCTIONS/SUBROUTINES ...

  10. VS2013下的64位与32位程序配置

    VS2013下的64位与32位程序配置   在Windows 7 64bit和Visual Studio 2013下生成64位程序. 新建一个Visual Studio Win32 Console项目 ...