Seems many of us got this problem: TLE for{1,1}!


  • 0
    H

    public class Solution {
    public ListNode insertionSortList(ListNode head) {

    	if(head==null||head.next==null) return head;
    	 
    	ListNode newHead=new ListNode(head.val);
    	ListNode curr=head.next;
    	while(curr!=null){
    		ListNode currNext=curr.next;
    		ListNode newcurr=newHead;
    		if(curr.val<=newHead.val){
    			ListNode oldHead=newHead;
    			newHead.val=curr.val;
    			newHead.next=oldHead;
    		}else{
    			while(newcurr.next!=null){
    				if(curr.val>newcurr.val&&curr.val<=newcurr.next.val){
    				ListNode oldcurr=newcurr.next;
    					newcurr.next=curr;
    					curr.next=oldcurr;	
    					
    				}
    				newcurr=newcurr.next;
    			}
    			if(newcurr.next==null&&curr.val>newcurr.val){
    				newcurr.next=curr;
    				curr.next=null;
    			}
    		}
    		curr=currNext;
    	}
    	return newHead;
    	
    } 
    }
    

    Tested by Eclipse, got right result. wondering why TEL...


  • 0
    M
       if(curr.val<=newHead.val){
            ListNode oldHead=newHead;
            newHead.val=curr.val;
            newHead.next=oldHead;
        }
    

    oldhead = newhead

    newHead.next = oldHead (newHead)

    newHead.next = newHead

    (curr = currNext) == null

    return newHead;

    RESULT:

    newHead->newHead->newHead->newHead->newHead->newHead->newHead->newHead->newHead...
    

    This is why you have the error, currently. The reason your algorithm works in eclipse is because you only are looking at the first two elements, not until you reach null, as leetcode's tester does. Change the middle line newHead.val = curr.val to newHead = curr and that portion should work.

    However, you are going to need to take care of the case when curr = oldHead.next at the start of that section. Otherwise, you'll go into another infinite loop when you try to insert something larger than the initial oldHead.


  • 0
    H

    very good! thank you for your help ! clear enough !


Log in to reply
 

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