当前位置:网站首页>leetcode--380.O(1) 时间插入、删除和获取随机元素
leetcode--380.O(1) 时间插入、删除和获取随机元素
2022-04-23 13:41:00 【爱学习的Amelia】
- 题目:实现
RandomizedSet
类:
RandomizedSet()
初始化RandomizedSet
对象bool insert(int val)
当元素val
不存在时,向集合中插入该项,并返回true
;否则,返回false
。bool remove(int val)
当元素val
存在时,从集合中移除该项,并返回true
;否则,返回false
。int getRandom()
随机返回现有集合中的一项(测试用例保证调用此方法时集合中至少存在一个元素)。每个元素应该有 相同的概率 被返回。
你必须实现类的所有函数,并满足每个函数的 平均 时间复杂度为O(1)
。1
- Example :
# Example 1
输入
["RandomizedSet", "insert", "remove", "insert", "getRandom", "remove", "insert", "getRandom"]
[[], [1], [2], [2], [], [1], [2], []]
输出
[null, true, false, true, 2, true, false, 2]
解释
RandomizedSet randomizedSet = new RandomizedSet();
randomizedSet.insert(1); // 向集合中插入 1 。返回 true 表示 1 被成功地插入。
randomizedSet.remove(2); // 返回 false ,表示集合中不存在 2 。
randomizedSet.insert(2); // 向集合中插入 2 。返回 true 。集合现在包含 [1,2] 。
randomizedSet.getRandom(); // getRandom 应随机返回 1 或 2 。
randomizedSet.remove(1); // 从集合中移除 1 ,返回 true 。集合现在包含 [2] 。
randomizedSet.insert(2); // 2 已在集合中,所以返回 false 。
randomizedSet.getRandom(); // 由于 2 是集合中唯一的数字,getRandom 总是返回 2 。
- 提示:
-231 <= val <= 231 - 1
- 最多调用
insert
、remove
和getRandom
函数2 * 105
次 - 在调用
getRandom
方法时,数据结构中 至少存在一个 元素。
- 解法一–列表:
class RandomizedSet:
def __init__(self):
self.element = []
self.index = 0
def insert(self, val):
if val in self.element:
return False
else:
self.element.append(val)
return True
def remove(self, val):
if val in self.element:
self.element.remove(val)
return True
else:
return False
def getRandom(self):
return random.choice(self.element)
- 解法二–集合:
class RandomizedSet:
def __init__(self):
self.element = []
self.index = 0
def insert(self, val):
if val in self.element:
return False
else:
self.element.append(val)
return True
def remove(self, val):
if val in self.element:
self.element.remove(val)
return True
else:
return False
def getRandom(self):
return random.choice(self.element)
- 总结:有一个错误要注意的地方,没有搞清楚类中定义的元素,假如你想要这个元素随着类的变化而变化,就把他定义到初始化方法里面,即
__init__
。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/insert-delete-getrandom-o1 ︎
版权声明
本文为[爱学习的Amelia]所创,转载请带上原文链接,感谢
https://blog.csdn.net/weixin_46361294/article/details/124361983
边栏推荐
- 这个SQL语名是什么意思
- GDB的使用
- [machine learning] Note 4. KNN + cross validation
- AttributeError: ‘dict‘ object has no attribute ‘iteritems‘
- Leetcode brush question 𞓜 13 Roman numeral to integer
- Two ways to deal with conflicting data in MySQL and PG Libraries
- Dolphin scheduler scheduling spark task stepping record
- Publish custom plug-ins to local server
- 【视频】线性回归中的贝叶斯推断与R语言预测工人工资数据|数据分享
- Reading notes: meta matrix factorization for federated rating predictions
猜你喜欢
Ai21 labs | standing on the shoulders of giant frozen language models
SQL learning window function
Apache Atlas Compilation and installation records
Cross carbon market and Web3 to achieve renewable transformation
OSS cloud storage management practice (polite experience)
Three characteristics of volatile keyword [data visibility, prohibition of instruction rearrangement and no guarantee of operation atomicity]
聯想拯救者Y9000X 2020
Set Jianyun x Feishu Shennuo to help the enterprise operation Department realize office automation
Why do you need to learn container technology to engage in cloud native development
AI21 Labs | Standing on the Shoulders of Giant Frozen Language Models(站在巨大的冷冻语言模型的肩膀上)
随机推荐
Operations related to Oracle partition
GDB的使用
[code analysis (1)] communication efficient learning of deep networks from decentralized data
Database transactions
Analysis of the problem that the cluster component GIPC in RAC environment cannot correctly identify the heartbeat network state
Core concepts of microservice architecture
SAP UI5 应用开发教程之七十二 - SAP UI5 页面路由的动画效果设置
Get the attribute value difference between two different objects with reflection and annotation
SSM project deployed in Alibaba cloud
Use of GDB
TIA博途中基於高速計數器觸發中斷OB40實現定點加工動作的具體方法示例
Double pointer instrument panel reading (I)
JS time to get this Monday and Sunday, judge the time is today, before and after today
MySQL [read / write lock + table lock + row lock + mvcc]
Django::Did you install mysqlclient?
[code analysis (2)] communication efficient learning of deep networks from decentralized data
Solution of discarding evaluate function in surprise Library
The interviewer dug a hole for me: how many concurrent TCP connections can a single server have?
Three characteristics of volatile keyword [data visibility, prohibition of instruction rearrangement and no guarantee of operation atomicity]
Express中间件③(自定义中间件)