-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathpickIndex.py
63 lines (47 loc) · 1.23 KB
/
pickIndex.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
import random
# Your Solution object will be instantiated and called as such:
# obj = Solution(w)
# param_1 = obj.pickIndex()
# Random Pick with Weight
import random
"""
time: N, pickindex lgn
space: N, 1
"""
class Solution:
def __init__(self, w):
self.w = list(itertools.accumulate(w))
def pickIndex(self):
return bisect.bisect_left(self.w, random.randint(1, self.w[-1]))
"""
time: N, pickindex lgn
space: N, 1
"""
class Solution:
def __init__(self, w: List[int]):
self.S = sum(w)
self.picks = []
total = 0
for i, weight in enumerate(w):
total += weight
self.picks.append(total)
def pickIndex(self) -> int:
i = random.randint(1, self.S)
l, r = 0, len(self.picks)
while l < r:
m = l + r >> 1
if self.picks[m] >= i:
r = m
else:
l = m + 1
return l
import random
"""
time: N, pickindex lgn
space: N, 1
"""
class Solution:
def __init__(self, w):
self.w = w
def pickIndex(self):
return random.choices(range(len(self.w)), weights=self.w)[0]