https://leetcode.com/submissions/detail/28015840/
Merge k Sorted Lists
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
Direct use of the method written in "Merge-Sorted Lists".
Http://www.cnblogs.com/Liok3187/p/4514347.html
22 comparison is good, each round of comparison will reduce the number of half lists.
1 /**2 * Definition for singly-linked list.3 * Function ListNode (val) {4 * This.val = val;5 * this.next = null;6 * }7 */8 /**9 * @param {listnode[]} listsTen * @return {ListNode} One */ A varMergeklists =function(lists) { - functionmergetwolists (L1, L2) { - if(L1 && L2 && l1.val!== undefined && l2.val!== undefined && l1.val >l2.val) { the varTMP =L1; -L1 =L2; -L2 =tmp; - } + vari = L1, j = L2, res = Curr = []; - if(I && i.val!==undefined) { +res = Curr =i; Ai =I.next; at}Else if(J && J.val!==undefined) { -res = Curr =J; -j =J.next; - } - while(I && J && i.val!== undefined && j.val!==undefined) { - if(I.val <j.val) { inCurr.next =i; -i =I.next; to}Else{ +Curr.next =J; -j =J.next; the } *Curr =Curr.next; $ }Panax Notoginseng if(I && i.val!==undefined) { -Curr.next =i; the}Else{ +Curr.next =J; A } the returnRes; + } - $ varK; $ while(Lists.length >= 2){ - varTmplist = []; - for(k = lists.length-1; k >= 0; k-=2){ theTmplist.push (Mergetwolists (lists[k), lists[k-1])); - }Wuyi if(k = = 0){ theTmplist.push (lists[0]); - } WuLists =tmplist; - } About $ returnLists[0] | | []; -};
[Leetcode] [JavaScript] Merge k Sorted Lists