heeeeelp! why is my solution is "Time Limit Exceeded"?


  • 0
    C
    //my way of selecet the list of has the min head node is "a-loop bubble sort". my code is following:
    public ListNode mergeKLists(ListNode[] lists) {
        ListNode dummy = new ListNode(0), rear = dummy;
        while(rear!=null){
            for(int i=0; i<lists.length-1; i++)
                if(lists[i+1]==null || (lists[i]!=null && lists[i+1].val>lists[i].val)) swap(lists, i, i+1);
            rear.next = lists[lists.length-1];
            rear = lists[lists.length-1];
            lists[lists.length-1] = rear==null? null:rear.next;
        }
        return dummy.next;
    }
    private void swap(ListNode[] lists, int i, int j){
        ListNode temp = lists[j];
        lists[j] = lists[i];
        lists[i] = temp;
    }

Log in to reply
 

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