-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path381-InsertDeleteGetRandomO1-DuplicatesAllowed.py
56 lines (45 loc) · 1.64 KB
/
381-InsertDeleteGetRandomO1-DuplicatesAllowed.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#思路: 参照380题,但是testcese一直不能通过,最后参考别人把getRandom中获取随机数的方式从random.randint换成random.randrange就AC了
# 原因不明,以后再看看 现在夜里2点了
import random
class RandomizedCollection(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.RandomList = []
def insert(self, val):
"""
Inserts a value to the collection. Returns true if the collection did not already contain the specified element.
:type val: int
:rtype: bool
"""
exist = True
if val in self.RandomList:
exist = False
self.RandomList.append(val)
return exist
def remove(self, val):
"""
Removes a value from the collection. Returns true if the collection contained the specified element.
:type val: int
:rtype: bool
"""
if val in self.RandomList:
key = self.RandomList.index(val)
self.RandomList.pop(key)
return True
return False
def getRandom(self):
"""
Get a random element from the collection.
:rtype: int
"""
if not self.RandomList:
return None
randomNum = random.randrange(0, len(self.RandomList))
return self.RandomList[randomNum-1]
# Your RandomizedCollection object will be instantiated and called as such:
# obj = RandomizedCollection()
# param_1 = obj.insert(val)
# param_2 = obj.remove(val)
# param_3 = obj.getRandom()https://leetcode-cn.com/submissions/detail/6675144/