[Python 109ms] Why my solution is fast than others?


  • 5
    L

    I just use a while loop to find duplicates. And my runtime is 109ms.

    A common runtime in python is 200ms ~ 400ms.

    # Definition for singly-linked list.
    # class ListNode:
    #     def __init__(self, x):
    #         self.val = x
    #         self.next = None
    
    class Solution:
        # @param head, a ListNode
        # @return a ListNode
        def deleteDuplicates(self, head):
            if head == None:
                return head
                
            node = head
            
            while node.next:
                if node.val == node.next.val:
                    node.next = node.next.next
                else:
                    node = node.next
                    
            return head

  • 0
    P

    Same algorithm as yours but got 116 ms.


  • 7
    H

    94ms. use the internal while will make you code fast, pretty, short, and pythonic

    class Solution:
        # @param head, a ListNode
        # @return a ListNode
        def deleteDuplicates(self, head):
            node = head
            while node:
                while node.next and node.next.val == node.val:
                    node.next = node.next.next
                    
                node = node.next
                
            return head

  • 0
    F

    Not Possible, two while loop and 94 ms ?


  • 1

    @fatmazaman Why would that not be possible?


  • 1
    I

    Agreed. Two while loops doesn't imply an O(n^2) algorithm.


  • 0
    P

    Just curious, what is the best way to time the function? Do you copy the code into local IDE or time it in the browser?


  • 0
    R

    I'm wondering that too. If you time it in local environment you have to the testcase as the OJ. While the online timer is unstable depending on the server status. So I doubt there's a fair way to race with others speed


Log in to reply
 

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