Time exceed problem! need help


  • 0
    S

    I dont under stand why my solution will time exceed. The process is to insert the node, then reset the connection of the node's original position. Can anyone help me solve it?

    public class Solution {
            public ListNode insertionSortList(ListNode head) {
                ListNode fakehead = new ListNode(Integer.MIN_VALUE);
                fakehead.next = head;
                ListNode target_pre = fakehead;
                while(target_pre.next != null) {
                    ListNode ptr = fakehead;
                    ListNode next = target_pre.next;
                    while(ptr.next.val <= target_pre.next.val && ptr.next != target_pre.next) {
                        ptr = ptr.next;
                    }
                    insert(ptr, target_pre);
                    target_pre = next;
                }
                
                return fakehead.next;
            }
            
            public void insert(ListNode insert_pot, ListNode target_pre) {
                ListNode target = target_pre.next;
                target_pre.next = target_pre.next.next;
                target.next = insert_pot.next;
                insert_pot.next = target;
            }
        }

Log in to reply
 

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