Time limited exceed for{1,1}


  • 0
    D

    I test this code using eclipse, it works right, however leetcode tell me it is time limited exceed, who can help me to find problem, thank you!

    public class Solution {
    
        public ListNode insertionSortList(ListNode head) {
    		
    	    if(head==null||head.next==null) return head;
    		ListNode headNode=head;	
    		ListNode currentNode=headNode.next;
    		ListNode nextNode = null;
    		
    		while(currentNode!=null){
    			nextNode= currentNode.next;
    			//when the node is smaller than headNode, insert it befor headNode
    			if(currentNode.val<headNode.val){
    				currentNode.next=headNode;
    				headNode=currentNode;
    				
    			//when the node is greater than or equal to the headNode, compare with the next node	
    			}else {
    				ListNode cmpNode = headNode;
    				while(cmpNode.next!=null&¤tNode.val>cmpNode.next.val){
    					cmpNode=cmpNode.next;
    				}
    				
    				if(currentNode.val<=cmpNode.next.val){
    				    currentNode.next=cmpNode.next;
    				    cmpNode.next=currentNode;	
    				}
    			}
    			currentNode=nextNode;	
    		}
    		return headNode;
    	}
    }

  • 0
    S

    Thanks for your post. I just updated your post with correct code format, hope you will pay attention next time.


  • 0
    S

    For the test case {1, 1}, your code will run these lines.

                if(currentNode.val<=cmpNode.next.val){
                    currentNode.next=cmpNode.next;   // the 2nd ListNode(1) will set its next value to itself. 
                    cmpNode.next=currentNode;   
                }
    

    I guess it will lead the judger to endless loop when parse your result.


  • 0
    D

    I find it, thank you very much!


Log in to reply
 

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