Why time limit exceeded


  • 0
    M
    //Algo:
    //a)Find preM & postN nodes.
    //b)Reverse between m & n
    public class Solution {
        public ListNode reverseBetween(ListNode head, int m, int n) {
           
           if(head==null || m==n )
            return head;
           
           ListNode preHead = new ListNode(-1);
           preHead.next = head;
           ListNode preM = preHead;
           ListNode postN = preHead;
           ListNode curr = preHead;
           ListNode mNode = null;
           ListNode nNode = null;
           int count = 0;
           
           while(count<m || count<=n)
           {
               if(count<m && preM!=null)
                preM = preM.next;
            
               if(count<=n && postN!=null)
                postN = postN.next;
           }
           
           if(preM!=null)
            mNode = preM.next;
           
           if(postN!=null)
           {
            nNode = postN;
            postN = postN.next;
           }
           
           reverse(preM, mNode, nNode, postN);
           return preHead.next;
        }
        
        public void reverse(ListNode preM, ListNode mNode, ListNode nNode, ListNode postN)
        {
            ListNode prev = preM;
            ListNode curr = mNode;
            
            while(curr!=postN)
            {
                ListNode next = curr.next;
                curr.next = prev;
                prev = curr;
                curr = next;
            }
            
           //Adjust endpoints
           nNode.next=null;
           preM.next = nNode;
           mNode.next = postN;
            
        }
    }

Log in to reply
 

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