-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
random-pick-index.py
56 lines (42 loc) · 1.08 KB
/
random-pick-index.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
# Time: ctor: O(n)
# pick: O(1)
# Space: O(n)
from random import randint
import collections
class Solution(object):
def __init__(self, nums):
"""
:type nums: List[int]
"""
self.__lookup = collections.defaultdict(list)
for i, x in enumerate(nums):
self.__lookup[x].append(i)
def pick(self, target):
"""
:type target: int
:rtype: int
"""
return self.__lookup[target][randint(0, len(self.__lookup[target])-1)]
# Time: ctor: O(1)
# pick: O(n)
# Space: O(1)
from random import randint
class Solution_TLE(object):
def __init__(self, nums):
"""
:type nums: List[int]
"""
self.__nums = nums
def pick(self, target):
"""
:type target: int
:rtype: int
"""
reservoir = -1
n = 0
for i in xrange(len(self.__nums)):
if self.__nums[i] != target:
continue
reservoir = i if randint(1, n+1) == 1 else reservoir
n += 1
return reservoir