-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path398 Random Pick Index.py
74 lines (61 loc) · 1.81 KB
/
398 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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
"""
Given an array of integers with possible duplicates, randomly output the index of a given target number. You can assume
that the given target number must exist in the array.
Note:
The array size can be very large. Solution that uses too much extra space will not pass the judge.
Example:
int[] nums = new int[] {1,2,3,3,3};
Solution solution = new Solution(nums);
// pick(3) should return either index 2, 3, or 4 randomly. Each index should have equal probability of returning.
solution.pick(3);
// pick(1) should return 0. Since in the array only nums[0] is equal to 1.
solution.pick(1);
Author: Rajeev Ranjan
"""
import random
class Solution(object):
def __init__(self, nums):
"""
:type nums: List[int]
"""
self.A = nums
def pick(self, target):
"""
O(n)
Reservoir Sampling
:type target: int
:rtype: int
"""
sz = 0
ret = None
for idx, val in enumerate(self.A):
if val == target:
sz += 1
p = random.randrange(0, sz)
if p == 0:
ret = idx
return ret
class SolutionError(object):
def __init__(self, nums):
"""
Reservoir Sampling
Assume pick is only called once
:type nums: List[int]
"""
self.d = {}
for idx, val in enumerate(nums):
if val not in self.d:
self.d[val] = (idx, 1)
else:
prev, sz = self.d[val]
p = random.randrange(0, sz)
if p < sz:
self.d[val] = (idx, sz + 1)
else:
self.d[val] = (prev, sz + 1)
def pick(self, target):
"""
:type target: int
:rtype: int
"""
return self.d[target][0]