O(n) and O(1) space Python solution


  • 0
    3

    Implementation of "Simple Solution" described in https://gregable.com/2007/10/reservoir-sampling.html.

    import random
    
    
    class Solution(object):
    
        def __init__(self, head):
            self.head = head
    
        def getRandom(self):
            curr = self.head
            selected_node = None
            max_val = 0
            while curr is not None:
                val = random.random()
                if val > max_val:
                    max_val = val
                    selected_node = curr
                curr = curr.next
            return selected_node.val
    

Log in to reply
 

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