LeetCode 23. Merge k Sorted Lists
原题链接在这里:https://leetcode.com/problems/merge-k-sorted-lists/
题目:
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
题解:
是Merge Two Sorted Lists的进阶版,现在是k条,用divide and conquer, 两条两条合并 最后合并成一个大的。
Note: mergeSort中别忘了最后的返回值是lists[l].
分析时间复杂度T(k) = 2T(k/2) + O(nk). k = lists.length, n是原数组中最长的list的长度。根据master theorem, Time Complexity: O(nk*logk).
Space: O(logk) 是recursion tree的高度。
AC Java:
1 /** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode(int x) { val = x; } 7 * } 8 */ 9 public class Solution { 10 public ListNode mergeKLists(ListNode[] lists) { 11 if(lists == null || lists.length == 0){ 12 return null; 13 } 14 return mergeSort(lists, 0, lists.length-1); 15 } 16 17 private ListNode mergeSort(ListNode[] lists, int l, int r){ 18 if(l == r){ 19 return lists[l]; 20 } 21 int m = l+(r-l)/2; 22 ListNode leftList = mergeSort(lists, l, m); 23 ListNode rightList = mergeSort(lists, m+1, r); 24 return merge(leftList, rightList); 25 } 26 27 private ListNode merge(ListNode l1, ListNode l2){ 28 if(l1 == null){ 29 return l2; 30 } 31 32 ListNode dummy = new ListNode(0); 33 ListNode cur = dummy; 34 while(l1 != null && l2 != null){ 35 if(l1.val <= l2.val){ 36 cur.next = l1; 37 l1 = l1.next; 38 cur = cur.next; 39 }else{ 40 cur.next = l2; 41 l2 = l2.next; 42 cur = cur.next; 43 } 44 } 45 if(l1 != null){ 46 cur.next = l1; 47 } 48 if(l2 != null){ 49 cur.next = l2; 50 } 51 return dummy.next; 52 } 53 }
Could use minHeap.
Time Complexity: O(nk * logk).
Space: O(k).
AC Java:
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 if(lists == null || lists.length == 0){ 14 return null; 15 } 16 17 ListNode dummy = new ListNode(-1); 18 ListNode it = dummy; 19 PriorityQueue<ListNode> minHeap = new PriorityQueue<ListNode>((a, b) -> a.val - b.val); 20 for(ListNode node : lists){ 21 if(node != null){ 22 minHeap.add(node); 23 } 24 } 25 26 while(!minHeap.isEmpty()){ 27 ListNode cur = minHeap.poll(); 28 it.next = cur; 29 it = it.next; 30 31 if(cur.next != null){ 32 minHeap.add(cur.next); 33 } 34 } 35 36 return dummy.next; 37 } 38 }