Python reservoir sampling solution.

  • 2

    class Solution(object):

    def __init__(self, nums):
        self.nums = nums
    def pick(self, target):
        res = None
        count = 0
        for i, x in enumerate(self.nums):
            if x == target:
                count += 1
                chance = random.randint(1, count)
                if chance == count:
                    res = i
        return res

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.