Python Reservoir Sampling


  • 0
    class Solution(object):
    
        def __init__(self, nums):
            self.nums = nums
    
        def pick(self, target):
            cnt, ans = 0 , -1
            for i in xrange(len(self.nums)):
                if self.nums[i] == target:
                    cnt += 1
                    if cnt == 1 or random.randint(1, cnt) == 1:
                        ans = i
            return ans
    

Log in to reply
 

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