Why TLE for case [3,5] 1,2? Adding the NewHead one by one...


  • 0
    W

    I trying to add from newHead one by one, move the head to the next, if head is m, add n to newHead's current pointer, if head is n, add m to newHead current pointer. But it gives TLE for [3,5] 1,2

    public ListNode reverseBetween(ListNode head, int m, int n) {
            if(m==n) return head;
            ListNode nodeM=head;
            ListNode nodeN=head;
            ListNode newHead=new ListNode(0);
            ListNode current=newHead;
            
            while(m>1){
                nodeM=nodeM.next;
                m--;
            }
            while(n>1){
                nodeN=nodeN.next;
                n--;
            }
            while(head!=null){
                if(head.val==nodeM.val)
                    current.next=nodeN;
                else if(head.val==nodeN.val)
                    current.next=nodeM;
                else
                    current.next=head;
                head=head.next;
                current=current.next;
            }
            return newHead.next;
        }

Log in to reply
 

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