Why does this solution get TLE error? It is O(n) I think


  • 0
    G
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
            ListNode hA = headA;
            ListNode hB = headB;
            int lenA = 0, lenB = 0;
            while(hA != null) {
                lenA++;
                hA = hA.next;
            }
            while(hB != null) {
                lenB++;
                hA = hB.next;
            }
            while(lenA > lenB) {
                headA = headA.next;
                lenA--;
            }
            while(lenA < lenB) {
                headB = headB.next;
                lenB--;
            }
            while(headA != headB) {
                headA = headA.next;
                headB = headB.next;
            }
            return headA;
        }

Log in to reply
 

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