标签:nbsp fun lis null list parse var output style
23. Merge k Sorted Lists
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
Example:
Input: [ 1->4->5, 1->3->4, 2->6 ] Output: 1->1->2->3->4->4->5->6
题意:按大小顺序合并n条链表
代码如下:
/** * Definition for singly-linked list. * function ListNode(val) { * this.val = val; * this.next = null; * } */ /** * @param {ListNode[]} lists * @return {ListNode} */ var mergeKLists = function(lists) { if(lists.length===0) return null; var n=lists.length; while(n>1){ var k=parseInt((n+1)/2); for(var i=0;i<parseInt(n/2);i++){ lists[i]= mergeTwoLists(lists[i],lists[i+k]); } n=k; } return lists[0]; }; var mergeTwoLists=function(list1,list2){ var head=new ListNode(-1); var curr=head; while(list1 && list2){ if(list1.val<list2.val){ curr.next=list1; list1=list1.next; }else{ curr.next=list2; list2=list2.next; } curr=curr.next; } if(list1) curr.next=list1; if(list2) curr.next=list2; return head.next; }
标签:nbsp fun lis null list parse var output style
原文地址:https://www.cnblogs.com/xingguozhiming/p/10387376.html