标签:lan queue code www tar span nod ide class
合并K个有序链表。题目即是题意,例子,
Example:
Input: [ 1->4->5, 1->3->4, 2->6 ] Output: 1->1->2->3->4->4->5->6
这个题的最优解应该是用priority queue解决但是因为JS实现PQ太过麻烦,所以我这里给出次优解,用21. Merge Two Sorted Lists的思路,分治法做。
时间O(nlogk) - k是链表的数量
空间O(n)
1 /** 2 * @param {ListNode[]} lists 3 * @return {ListNode} 4 */ 5 var mergeKLists = function (lists) { 6 return divide(lists, 0, lists.length - 1); 7 }; 8 9 var divide = function (lists, start, end) { 10 if (start === end) { 11 return lists[start]; 12 } else if (start < end) { 13 const mid = parseInt(start + (end - start) / 2); 14 const left = divide(lists, start, mid); 15 const right = divide(lists, mid + 1, end); 16 return merge(left, right); 17 } else { 18 return null; 19 } 20 } 21 22 var merge = function (left, right) { 23 if (!left) { 24 return right; 25 } else if (!right) { 26 return left; 27 } else if (left.val < right.val) { 28 left.next = merge(left.next, right); 29 return left; 30 } else { 31 right.next = merge(left, right.next); 32 return right; 33 } 34 }
[LeetCode] 23. Merge k Sorted Lists
标签:lan queue code www tar span nod ide class
原文地址:https://www.cnblogs.com/aaronliu1991/p/12239444.html