forked from JediXL/LeetCodeByPython
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path398_Random_Pick_Index.py
47 lines (36 loc) · 974 Bytes
/
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
'''
@auther: Jedi.L
@Date: Wed, May 8, 2019 11:11
@Email: [email protected]
@Blog: www.tundrazone.com
'''
import random
# beats 100%
class Solution1:
def __init__(self, nums):
self.nums = nums
def pick(self, target):
e = self.nums.count(target)
# ranodom select the i-th object
i = random.randint(1, e)
# count 1 to i
for j in range(len(self.nums)):
if self.nums[j] == target:
i = i - 1
if i = 0:
return j
# beats 50%
class Solution2:
def __init__(self, nums):
self.nums = nums
def pick(self, target):
candid =[]
for i in range(len(self.nums)):
if self.nums[i] == target:
candid.append(i)
return random.sample(candid, 1)
s = Solution([1])
print(s.pick(1))
# Your Solution object will be instantiated and called as such:
# obj = Solution(nums)
# param_1 = obj.pick(target)