Clear code but cost 276ms :( how can i reach the 50ms line ?


  • 4
    C
     ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
         ListNode *pa = headA, *pb = headB;
         while(pa && pb){
             pa = pa->next;
             pb = pb->next;
         }
         while(pa){
             headA = headA->next;
             pa = pa->next;
         }
         while(pb){
             headB = headB->next;
             pb = pb->next;
         }
         while(headA && headA != headB){
             headA = headA->next;
             headB = headB->next;
         }
         return headA;
     }

  • 4
    S

    You code is already very efficient as it stands now. The author of this question (which is me by the way) deliberately used many long test cases in order to distinguish O(n) from O(n^2) algorithms. Plus, extra time is spent on validating whether the lists have been modified. So I would say 200~300ms is already as fast as you can get given the performance of the OJ server. Don't worry too much about it.


  • 0
    F

    very helpful


  • 0
    S

    As the problem describes: The linked lists must retain their original structure after the function returns.
    But this solution changed headA and headB, then lost the head points of A and B.


Log in to reply
 

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