当前位置:网站首页>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
边栏推荐
- Antd design form verification
- Small case of web login (including verification code login)
- SQL learning | set operation
- AI21 Labs | Standing on the Shoulders of Giant Frozen Language Models(站在巨大的冷冻语言模型的肩膀上)
- MySQL and PgSQL time related operations
- Storage scheme of video viewing records of users in station B
- Operations related to Oracle partition
- Analysis of cluster component gpnp failed to start successfully in RAC environment
- 零拷贝技术
- Detailed explanation of constraints of Oracle table
猜你喜欢

QT calling external program

On the bug of JS regular test method

Solution of discarding evaluate function in surprise Library

Ai21 labs | standing on the shoulders of giant frozen language models

Static interface method calls are not supported at language level '5'

JUC interview questions about synchronized, ThreadLocal, thread pool and atomic atomic classes

Cross carbon market and Web3 to achieve renewable transformation

【视频】线性回归中的贝叶斯推断与R语言预测工人工资数据|数据分享

Example of specific method for TIA to trigger interrupt ob40 based on high-speed counter to realize fixed-point machining action

自动化的艺术
随机推荐
What does the SQL name mean
Modification of table fields by Oracle
切线空间(tangent space)
UML统一建模语言
At the same time, the problems of height collapse and outer margin overlap are solved
[Video] Bayesian inference in linear regression and R language prediction of workers' wage data | data sharing
The difference between is and as in Oracle stored procedure
Move blog to CSDN
SQL learning | set operation
Using Jupiter notebook in virtual environment
Reading notes: fedgnn: Federated graph neural network for privacy preserving recommendation
JS time to get this Monday and Sunday, judge the time is today, before and after today
Opening: identification of double pointer instrument panel
Information: 2021 / 9 / 29 10:01 - build completed with 1 error and 0 warnings in 11S 30ms error exception handling
聯想拯救者Y9000X 2020
Detailed explanation of Oracle tablespace table partition and query method of Oracle table partition
Tensorflow & pytorch common error reporting
校园外卖系统 - 「农职邦」微信原生云开发小程序
Interval query through rownum
[code analysis (1)] communication efficient learning of deep networks from decentralized data