Why is my solution wrong?


  • 0
    R
    import random
    class ListNode(object):
        def __init__(self, x):
            self.val = x
            self.next = None
    
    
    head= ListNode(2)
    head.next = ListNode(3)
    head.next.next = ListNode(4)
    class Solution(object):
        def __init__(self, head):
            self.head = head
            length = 1
            tmp = self.head.next
            while tmp is not None:
                length += 1
                tmp = tmp.next
            self.length = length
        
        def getRandom(self):
            index = random.randrange(0, self.length)
            tmp = self.head
            while index > 0:
                tmp = tmp.next
                index -= 1
            return tmp
    
    a = Solution(head=head)
    print(a.getRandom().val)
    

    The input is:

    ["Solution","getRandom"]
    [[[1,2,3]],[]]
    

    Your answer:

    [null,[3]]
    

    Expected answer:

    [null,3]
    

  • 0

    return tmp.val instead of tmp


Log in to reply
 

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