Random Pick Index
根据geeksforgeeks里面的提到的一种随机算法做的:Resorvoir sampling(水库取样),根据个人理解就是遍历整个集合找到符合要求的数据时就扩充一次样本,然后在扩充的样本里面进行一次随机抽取来同时维持数据的正确性以及在正确范围条件下的随机性
class Solution(object):
def __init__(self, nums):
"""
:type nums: List[int]
:type numsSize: int
"""
self.nums = nums
def pick(self, target):
"""
:type target: int
:rtype: int
"""
res = None
count = 1
for index, val in enumerate(self.nums):
if val == target:
if random.randint(1, count) == 1:
res = index
count += 1
return res