Python Reservoir Sampling


  • 0
    class Solution(object):
    
        def __init__(self, head):
            self.h = head
    
        def getRandom(self):
            ans, cnt, h = -1, 0, self.h
            while h:
                cnt += 1
                if random.randint(1, cnt) == 1:
                    ans = h.val
                h = h.next
            return ans
    

Log in to reply
 

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