题目链接: https://leetcode.com/problems/merge-k-sorted-lists/
1. 题目介绍(合并k个排序链表)
You are given an array of k linked-lists lists, each linked-list is sorted in ascending order.
【Translate】: 给你一个由k个链表组成的数组,每个链表都是按升序排序的。
Merge all the linked-lists into one sorted linked-list and return it.
【Translate】: 合并所有链表到一个排序链表,并返回它。
【测试用例】:
【约束】:
2. 题解
2.1 冒泡合并 – O(n2)
恰好前两天做过Merge Two Sorted Lists这道题,所以我就想着能不能把现在的这道题转换成合并两个排序链表,所以就有了以下题解。确实可以,但是效率不高。核心思想就是先定义一个初始值为最小的节点,然后让它先与第一个链表合并,然后再将合并后的结果继续与下一个链表合并,直到全部合并完毕。
public ListNode mergeTwoLists(ListNode l1, ListNode l2){
if(l1 == null) return l2;
if(l2 == null) return l1;
if(l1.val < l2.val){
l1.next = mergeTwoLists(l1.next, l2);
return l1;
} else{
l2.next = mergeTwoLists(l1, l2.next);
return l2;
}
}
public ListNode mergeKLists(ListNode[] lists) {
int k = lists.length;
ListNode curr = new ListNode(Integer.MIN_VALUE);
for (int i = 0; i < k; i++)
{
curr = mergeTwoLists(curr,lists[i]);
// System.out.println(curr.val);
// System.out.println(curr.next.val);
}
return curr.next;
}
2.2 Priority Queue – O(n)
chintant在 A java solution based on Priority Queue 的评论中给出的题解。他将所有的元素都存入PriorityQueue,利用PriorityQueue的Comparator自动将其排序,然后再相连成一个新的链表。
class Solution {
public ListNode mergeKLists(ListNode[] lists) {
if (lists==null || lists.length==0) return null;
PriorityQueue<ListNode> queue= new PriorityQueue<ListNode>(lists.length, (a,b)-> a.val-b.val);
ListNode dummy = new ListNode(0);
ListNode tail=dummy;
for (ListNode node:lists)
if (node!=null)
queue.add(node);
while (!queue.isEmpty()){
tail.next=queue.poll();
tail=tail.next;
if (tail.next!=null)
queue.add(tail.next);
}
return dummy.next;
}
}
2.3 recursion – O(nlogk)
mouqi123提供的题解 My simple java Solution use recursion ,从0到k-1遍历,分区合并。
考虑这个例子:
列表 = [1,2,3,4] 其中 1,2,3,4 是列表
我们将对列表进行分区并合并 1 和 2,将其设为 M1 然后我们取第二个分区并合并 3 和 4,将其设为 M2。
为了完成任务,我们需要在合并 M1 和 M2 的地方进行第三次合并 M3。
public static ListNode mergeKLists(ListNode[] lists){
return partion(lists,0,lists.length-1);
}
public static ListNode partion(ListNode[] lists,int s,int e){
if(s==e) return lists[s];
if(s<e){
int q=(s+e)/2;
ListNode l1=partion(lists,s,q);
ListNode l2=partion(lists,q+1,e);
return merge(l1,l2);
}else
return null;
}
//This function is from Merge Two Sorted Lists.
public static ListNode merge(ListNode l1,ListNode l2){
if(l1==null) return l2;
if(l2==null) return l1;
if(l1.val<l2.val){
l1.next=merge(l1.next,l2);
return l1;
}else{
l2.next=merge(l1,l2.next);
return l2;
}
}