forked from shuboc/LeetCode-2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
random-pick-with-blacklist.py
108 lines (94 loc) · 2.46 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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
# Time: ctor: O(b)
# pick: O(1)
# Space: O(b)
# Given a blacklist B containing unique integers from [0, N),
# write a function to return a uniform random integer from
# [0, N) which is NOT in B.
#
# Optimize it such that it minimizes the call to system’s Math.random().
#
# Note:
#
# 1 <= N <= 1000000000
# 0 <= B.length < min(100000, N)
# [0, N) does NOT include N. See interval notation.
# Example 1:
#
# Input:
# ["Solution","pick","pick","pick"]
# [[1,[]],[],[],[]]
# Output: [null,0,0,0]
# Example 2:
#
# Input:
# ["Solution","pick","pick","pick"]
# [[2,[]],[],[],[]]
# Output: [null,1,1,1]
# Example 3:
#
# Input:
# ["Solution","pick","pick","pick"]
# [[3,[1]],[],[],[]]
# Output: [null,0,0,2]
# Example 4:
#
# Input:
# ["Solution","pick","pick","pick"]
# [[4,[2]],[],[],[]]
# Output: [null,1,3,1]
# Explanation of Input Syntax:
#
# The input is two lists: the subroutines called and
# their arguments. Solution's constructor has two arguments,
# N and the blacklist B.
# pick has no arguments.
# Arguments are always wrapped with a list,
# even if there aren't any.
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
# Your Solution object will be instantiated and called as such:
# obj = Solution(N, blacklist)
# param_1 = obj.pick()