Any Python Code faster than 120ms?


  • 0
    W

    I have been searching for a faster solution for long.

    My solution is attached below (with the analysis under the help of line_profiler package). The solution is turned out to be exactly the same with cakehe's solutionHere. It scores 148ms, which is only at bottom 24%. To be honest, I thought this neat code should not rank that low.

    Is there any awesome solution? I am just curious and want to see what a better one looks like.

    Line #      Hits         Time  Per Hit   % Time  Line Contents
    ==============================================================
        27                                               def addTwoNumbers(self, l1, l2):
        28                                                   """
        29                                                   :type l1: ListNode
        30                                                   :type l2: ListNode
        31                                                   :rtype: ListNode
        32                                                   """
        33         2           10     5.0     12.2          lsum = current = ListNode(0)
        34         2            3      1.5      3.7          num =  0
        35         8            8      1.0      9.8          while l1 or l2 or num:
        36         6            6      1.0      7.3              if l1:
        37         4            5      1.2      6.1                  num += l1.val
        38         4            4      1.0      4.9                  l1 = l1.next
        39         6            5      0.8      6.1              if l2:
        40         6            6      1.0      7.3                  num += l2.val
        41         6            5      0.8      6.1                  l2 = l2.next
        42         6           17      2.8     20.7              current.next = ListNode(num % 10)
        43         6            6      1.0      7.3              current = current.next
        44         6            5      0.8      6.1              num //= 10
        45
        46         2            2      1.0      2.4          return lsum.next
    

Log in to reply
 

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