当前位置:网站首页>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
RandomizedSet
class :
RandomizedSet()
initializationRandomizedSet
objectbool insert(int val)
When elementval
When there is no , Insert the item into the collection , And back totrue
; otherwise , returnfalse
.bool remove(int val)
When elementval
In 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
、remove
andgetRandom
function2 * 105
Time - Calling
getRandom
When 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
边栏推荐
猜你喜欢
3300万IOPS、39微秒延迟、碳足迹认证,谁在认真搞事情?
Port occupied 1
33 million IOPs, 39 microsecond delay, carbon footprint certification, who is serious?
Taobao released the baby prompt "your consumer protection deposit is insufficient, and the expiration protection has been started"
Record a strange bug: component copy after cache component jump
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
elmo(BiLSTM-CRF+elmo)(Conll-2003 命名实体识别NER)
Basic knowledge learning record
mysql新表,自增id长达20位,原因竟是......
Chapter I review of e-commerce spike products
随机推荐
CentOS mysql多实例部署
金蝶云星空API调用实践
微信小程序 input隐藏和不可操作的设置
33 million IOPs, 39 microsecond delay, carbon footprint certification, who is serious?
smart-doc + torna生成接口文档
基于微信小程序的wifi模块使用
org.apache.parquet.schema.InvalidSchemaException: A group type can not be empty. Parquet does not su
Postman reference summary
Express middleware ③ (custom Middleware)
Android篇:2019初中级Android开发社招面试解答(中
JMeter pressure test tool
PySide2
cnpm的诡异bug
微信小程序setInterval定时函数使用详细教程
关于pthread多线程一些好文章
关于stream流,浅记一下------
微信小程序的订阅号开发(消息推送)
redis如何解决缓存雪崩、缓存击穿和缓存穿透问题
JS force deduction brush question 102 Sequence traversal of binary tree
Oracle alarm log alert Chinese trace and trace files