For python, why I cannot use random.random() function

  • 0

    class Solution(object):

    def __init__(self, head):
        self.h = head
    def getRandom(self):
        t = self.h
        ans = None
        i = 1
        while t:
            if random.randint(1, i) == 1: ans = t
            t =
            i += 1
        return ans.val

    This solution passes all tests. But if I change the random generator to

        while t:
            if random.random() <=  1/i: ans = t
            t =
            i += 1

    It cannot pass all tests.


Log in to reply

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