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
合并K个排序链表。题目即是题意。这个题的最优解应该是用priority queue解决但是因为JS实现PQ太过麻烦,所以JS实现我给出次优解,思路是merge sort。
时间O(nlogk) - k是链表的数量
空间O(n)
JavaScript实现
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 }
Java实现 - priority queue
时间O(nlogk) - k是链表的数量
空间O(n)
1 /** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode() {} 7 * ListNode(int val) { this.val = val; } 8 * ListNode(int val, ListNode next) { this.val = val; this.next = next; } 9 * } 10 */ 11 class Solution { 12 public ListNode mergeKLists(ListNode[] lists) { 13 // corner case 14 if (lists == null || lists.length == 0) { 15 return null; 16 } 17 18 // normal case 19 PriorityQueue<ListNode> queue = new PriorityQueue<>(lists.length, (a, b) -> a.val - b.val); 20 ListNode dummy = new ListNode(0); 21 ListNode cur = dummy; 22 for (ListNode list : lists) { 23 // 注意sublist有可能是空的 24 if (list != null) { 25 queue.add(list); 26 } 27 } 28 29 while (!queue.isEmpty()) { 30 cur.next = queue.poll(); 31 cur = cur.next; 32 if (cur.next != null) { 33 queue.add(cur.next); 34 } 35 } 36 return dummy.next; 37 } 38 }
相关题目