random pick index

🏠

It might be worth mentioning that the input is unsorted, at which point the linear search makes more sense.

 1 class Solution:
 2     def __init__(self, nums):
 3         self.nums = nums
 4 
 5     def pick(self, target):
 6         res = None
 7         count = 0
 8         for i, x in enumerate(self.nums):
 9             if x == target:
10                 count += 1
11                 chance = random.randint(1, count)
12                 if chance == count:
13                     res = i
14         return res
15 
16 
17 obj = Solution([1, 2, 3, 3, 3])
18 param_1 = obj.pick(3)