leetcode-mid-design-380. Insert Delete GetRandom O(1)
2024-10-07 07:10:02
mycode
import random
class RandomizedSet(object): def __init__(self):
"""
Initialize your data structure here.
"""
self.s = [] def insert(self, val):
"""
Inserts a value to the set. Returns true if the set did not already contain the specified element.
:type val: int
:rtype: bool
"""
if val in self.s: return False
else:
self.s.append(val)
return True def remove(self, val):
"""
Removes a value from the set. Returns true if the set contained the specified element.
:type val: int
:rtype: bool
"""
if val in self.s:
self.s.remove(val)
return True
else:
return False def getRandom(self):
"""
Get a random element from the set.
:rtype: int
"""
return self.s[random.randint(0,len(self.s)-1)] # Your RandomizedSet object will be instantiated and called as such:
# obj = RandomizedSet()
# param_1 = obj.insert(val)
# param_2 = obj.remove(val)
# param_3 = obj.getRandom()
参考:
emmmm。。。我直接调用的???我的天。。。
思路:用dic来查找,找到后去insert和删除
import random class RandomizedSet(object): def __init__(self):
self.data = []
self.pos = {} def insert(self, val):
if val in self.pos:
return False self.data.append(val)
self.pos[val] = len(self.data) - 1 return True def remove(self, val):
"""
Removes a value from the set. Returns true if the set contained the specified element.
:type val: int
:rtype: bool
"""
if val not in self.pos:
return False last = self.data[-1]
elt = self.pos[val]
self.data[elt] = last
self.pos[last] = elt
self.data.pop()
del self.pos[val] return True def getRandom(self):
return random.choice(self.data) # Your RandomizedSet object will be instantiated and called as such:
# obj = RandomizedSet()
# param_1 = obj.insert(val)
# param_2 = obj.remove(val)
# param_3 = obj.getRandom()
最新文章
- 关于hg的命令
- MVC项目
- IT职业思考 谈谈IT外包公司
- JS常用的function集合
- 彻底解决Eclipse自动补全变量名及变量名后面追加类型名
- jquery相关校验以及jquery其他知识总结
- 使用public key来做SSH authentication
- web_reg_find()查询信息为变量
- c#基础语言编程-正则表达式基础
- ASP.NET MVC Framework
- ExtJS4 便捷三层开发模式
- PreferencesUtils【SharedPreferences操作工具类】
- JS 获取链接中的参数
- Hibernate中的Entity类之间的继承关系之一MappedSuperclass
- 【转】Android 模拟器横屏竖屏切换设置
- Python机器学习笔记:深入学习Keras中Sequential模型及方法
- 调整innodb redo log files数目和大小的具体方法和步骤
- CSP201512-2:消除类游戏
- Linux iptables:规则原理和基础
- 关于HashSet在 java7 与 java8的不同
热门文章
- 在.NET Core 3.0中发布单个Exe文件(PublishSingleFile)
- 深入理解java虚拟机(4)类加载的过程
- RateLimiter 源码分析(Guava 和 Sentinel 实现)
- Vue安装与简单使用
- Java日志打印方法
- python之堆排序算法代码
- [转]为什么要引入nullptr?
- [HAOI2010]软件安装(Tarjan,树形dp)
- $.getJSON同步和异步
- MySQL中添加、修改、删除约束