当前位置:网站首页>leetcode--380. O (1) time insertion, deletion and acquisition of random elements
leetcode--380. O (1) time insertion, deletion and acquisition of random elements
2022-04-23 14:03:00 【Amelia who loves learning】
- subject : Realization
RandomizedSetclass :
RandomizedSet()initializationRandomizedSetobjectbool insert(int val)When elementvalWhen there is no , Insert the item into the collection , And back totrue; otherwise , returnfalse.bool remove(int val)When elementvalIn existence , Remove the item from the collection , And back totrue; otherwise , returnfalse.int getRandom()Random return of an item in an existing collection ( The test case guarantees that there is at least one element in the collection when this method is called ). Every element should have Same probability Returned .
You must implement all the functions of the class , And satisfy the of each function Average The time complexity isO(1).1
- Example :
# Example 1
Input
["RandomizedSet", "insert", "remove", "insert", "getRandom", "remove", "insert", "getRandom"]
[[], [1], [2], [2], [], [1], [2], []]
Output
[null, true, false, true, 2, true, false, 2]
explain
RandomizedSet randomizedSet = new RandomizedSet();
randomizedSet.insert(1); // Insert into collection 1 . return true Express 1 Successfully inserted .
randomizedSet.remove(2); // return false , Indicates that the collection does not exist 2 .
randomizedSet.insert(2); // Insert into collection 2 . return true . The collection now contains [1,2] .
randomizedSet.getRandom(); // getRandom Should return at random 1 or 2 .
randomizedSet.remove(1); // Remove from collection 1 , return true . The collection now contains [2] .
randomizedSet.insert(2); // 2 Already in collection , So back false .
randomizedSet.getRandom(); // because 2 Is the only number in the set ,getRandom Always returns 2 .
- Tips :
-231 <= val <= 231 - 1- Call at most
insert、removeandgetRandomfunction2 * 105Time - Calling
getRandomWhen the method is used , In the data structure There is at least one Elements .
- Solution 1 – list :
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)
- Solution 2 – aggregate :
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)
- summary : There is a mistake to pay attention to , Not clear about the elements defined in the class , If you want this element to change as the class changes , Just define it into the initialization method , namely
__init__.
source : Power button (LeetCode)
link :https://leetcode-cn.com/problems/insert-delete-getrandom-o1 ︎
版权声明
本文为[Amelia who loves learning]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204231341317245.html
边栏推荐
- JS 力扣刷题 103. 二叉树的锯齿形层序遍历
- Wechat applet
- 微信小程序进行蓝牙初始化、搜索附近蓝牙设备及连接指定蓝牙(一)
- CentOS mysql多实例部署
- 基于CM管理的CDH集群集成Phoenix
- The art of automation
- Scientists say Australian plan to cull up to 10,000 wild horses doesn’t go far enough
- Interesting talk about network protocol
- FBS(fman build system)打包
- Android interview theme collection
猜你喜欢

联想产品经理林林:天津当地网络运营商网络故障 ZUI系统后台服务器暂时无法正常工作

Quartus Prime硬件实验开发(DE2-115板)实验一CPU指令运算器设计

Chapter I review of e-commerce spike products
![Special test 05 · double integral [Li Yanfang's whole class]](/img/af/0d52a6268166812425296c3aeb8f85.png)
Special test 05 · double integral [Li Yanfang's whole class]

分库分表 & ShardingSphere

crontab定时任务输出产生大量邮件耗尽文件系统inode问题处理

Express middleware ③ (custom Middleware)

1256:献给阿尔吉侬的花束

Lin Lin, product manager of Lenovo: network failure of local network operator in Tianjin. The background server of Zui system can't work normally for the time being

PATH环境变量
随机推荐
AtCoder Beginner Contest 248C Dice Sum (生成函数)
1256: bouquet for algenon
分页SQL
Postman reference summary
About note 1
Redis docker 安装
生产环境——
How does redis solve the problems of cache avalanche, cache breakdown and cache penetration
Pytorch 经典卷积神经网络 LeNet
PySide2
jacob打印word
Decentralized Collaborative Learning Framework for Next POI Recommendation
33 million IOPs, 39 microsecond delay, carbon footprint certification, who is serious?
Program compilation and debugging learning record
JS brain burning interview question reward
腾讯根据ip解析地址
Ptorch classical convolutional neural network lenet
YARN线上动态资源调优
Oracle告警日志alert.log和跟踪trace文件中文乱码显示
org.apache.parquet.schema.InvalidSchemaException: A group type can not be empty. Parquet does not su