合并 k 个排序链表,返回合并后的排序链表。请分析和描述算法的复杂度。
示例:
输入:
[
1->4->5,
1->3->4,
2->6
]
输出: 1->1->2->3->4->4->5->6
解答:
复用LeetCode21合并两个链表的代码,将链表0和链表1进行合并生成新的链表,然后再将新的链表与链表2合并,依次类推。
时间复杂度为 m 2 ∗ n m^2*n m2∗n,其中m代表链表的个数,n代表链表元素的个数。
**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if (l1 == null) return l2;
if (l2 == null) return l1;
ListNode listNode = new ListNode(0);
ListNode head = listNode;
ListNode p = new ListNode(0);
while (l1 != null && l2 != null) {
if (l1.val <= l2.val) {
listNode.next = l1;
p = l1;
l1 = l1.next;
}
else{
listNode.next = l2;
p = l2;
l2 = l2.next;
}
listNode = listNode.next;
}
if (l1 == null) p.next = l2;
if (l2 == null) p.next = l1;
// l1 作为返回链表
return head.next;
}
public ListNode mergeKLists(ListNode[] lists) {
int len = lists.length;
if (len == 0) return null;
if (len == 1) return lists[0];
for (int i = 1; i < len; i++){
lists[0] = mergeTwoLists(lists[0], lists[i]);
}
return lists[0];
}
}
采用两两合并的方法,邻近的两个链表合并生成m/2个链表,再次两两合并,直至只剩下一个链表。时间复杂度为 O ( m l o g m ∗ n ) O(mlogm*n) O(mlogm∗n),其中m代表链表的个数,n代表链表元素的个数。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode mergeKLists(ListNode[] lists) {
if(lists ==null || lists.length == 0){
return null;
}
return sort(lists,0,lists.length-1);
}
public ListNode sort(ListNode[] lists , int lo ,int hi){
if(lo >= hi){return lists[lo];}
int mid = (hi-lo)/2+lo;
ListNode l1 = sort(lists,lo,mid);
ListNode l2 = sort(lists,mid+1,hi);
return merge(l1,l2);
}
public ListNode merge(ListNode l1, ListNode l2) {
ListNode h1 = l1;
ListNode h2 = l2;
ListNode res = new ListNode(0);
ListNode head = res;
while (h1 != null || h2 != null) {
if (h1 == null || h2 == null) {
head.next = h1 == null ? h2 : h1;
break;
}
//如果h2大于或等于h1
if (h1.val <= h2.val) {
head.next = h1;
h1 = h1.next;
head = head.next;
} else if (h1.val >= h2.val) {
head.next = h2;
h2 = h2.next;
head = head.next;
}
}
return res.next;
}
}