Python Reservpor Sampling


  • 0
    D

    With inspiration from This post

    from random import randint
    class Solution(object):
    
        def __init__(self, nums):
            """
            
            :type nums: List[int]
            :type numsSize: int
            """
            self.data = nums
    
        def pick(self, target):
            """
            :type target: int
            :rtype: int
            """
            r, c = 0, 0
            for i in range(len(self.data)):
                if self.data[i] != target: continue
                if randint(0, c) == 0: r = i
                c += 1
            return r
                
    
    # Your Solution object will be instantiated and called as such:
    # obj = Solution(nums)
    # param_1 = obj.pick(target)

Log in to reply
 

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