forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 1
/
random-pick-with-blacklist.py
62 lines (48 loc) · 1.34 KB
/
random-pick-with-blacklist.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
57
58
59
# Time: ctor: O(b)
# pick: O(1)
# Space: O(b)
import random
class Solution(object):
def __init__(self, N, blacklist):
"""
:type N: int
:type blacklist: List[int]
"""
self.__n = N-len(blacklist)
self.__lookup = {}
white = iter(set(range(self.__n, N))-set(blacklist))
for black in blacklist:
if black < self.__n:
self.__lookup[black] = next(white)
def pick(self):
"""
:rtype: int
"""
index = random.randint(0, self.__n-1)
return self.__lookup[index] if index in self.__lookup else index
# Time: ctor: O(blogb)
# pick: O(logb)
# Space: O(b)
import random
class Solution2(object):
def __init__(self, N, blacklist):
"""
:type N: int
:type blacklist: List[int]
"""
self.__n = N-len(blacklist)
blacklist.sort()
self.__blacklist = blacklist
def pick(self):
"""
:rtype: int
"""
index = random.randint(0, self.__n-1)
left, right = 0, len(self.__blacklist)-1
while left <= right:
mid = left+(right-left)//2
if index+mid < self.__blacklist[mid]:
right = mid-1
else:
left = mid+1
return index+left