Reservoir Sampling Python Solution


  • 0
    X

    '''
    Class Solution(object):

    def __init__(self, nums):
        self.l = nums
    
    def pick(self, target):
        index,count,nums = -1,0,self.l
        for i in range(len(nums)):
            if nums[i] == target:
                if index == -1:
                    index = i
                elif random.randint(0,count) == 0:
                    index = i
                count += 1
        return index
    

    '''


  • 2
    X

    I want to correct my answer. I could leave the case index == -1, since random.randint(0,0) always return 0, the first (num==target)'s index will assign to index automatically.

    def pick(self, target):
        index,count,nums = -1,0,self.l
        for i in range(len(nums)):
            if nums[i] == target:
                if random.randint(0,count) == 0:
                    index = i
                count += 1
        return index
    

    '''


Log in to reply
 

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