Leetcode 23. Merge k Sorted Lists合并k个排序链表

时间:2022-05-01 21:22:24

题目:Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
合并k个排序链表。
首先想到的是最简单的方法:遍历每个链表的头节点,找到最小的那个头节点加入到要输出链表的结尾(需要注意代码的鲁棒性,考虑输入有null链表的情况):

/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/

public class Solution {
public ListNode mergeKLists(ListNode[] lists) {
int length=lists.length;
if(length==0){
return null;
}
int min=0;
ListNode minNode=null;
int i=0;
int mini=0;
while(i<length&&lists[i]==null){
i++;
}
if(i==length){
return null;
}
mini=i;
min=lists[i].val;
minNode=lists[i];
while(i<length){
if(lists[i]!=null&&lists[i].val<min){
min=lists[i].val;
minNode=lists[i];
mini=i;
}
i++;
}
lists[mini]=(lists[mini]).next;
ListNode head=minNode;
ListNode temp=head;
while(minNode!=null){
minNode=null;
min=0;
i=0;
mini=0;
while(i<length&&lists[i]==null){
i++;
}
if(i==length){
break;
}
min=lists[i].val;
minNode=lists[i];
mini=i;
while(i<length){
if(lists[i]!=null&&lists[i].val<min){
min=lists[i].val;
minNode=lists[i];
mini=i;
}
i++;
}
temp.next=minNode;
temp=temp.next;
lists[mini]=(lists[mini]).next;
}
return head;

}
}

这种方法很不幸地超时了,上网查了一下注意到通过使用归并排序算法可将链表排序的时间复杂度缩减到的O(NlgN),具体代码如下:

/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/

public class Solution {
public ListNode mergeKLists(ListNode[] lists) {
if(lists.length==0){
return null;
}
return recmergeLists(lists,0,lists.length-1);
}
public ListNode recmergeLists(ListNode[] lists,int p, int q){
if(q>p){
int m=(q-p)/2+p;
return merge(recmergeLists(lists,p,m),recmergeLists(lists,m+1,q));
}else{
return lists[p];
}
}
public ListNode merge(ListNode n1,ListNode n2){
if(n1==null){
return n2;
}
if(n2==null){
return n1;
}
ListNode head=null;
if(n1.val<n2.val){
head=n1;
n1=n1.next;
}else{
head=n2;
n2=n2.next;
}
ListNode temp=head;
while(n1!=null&&n2!=null){
if(n1.val<n2.val){
temp.next=n1;
n1=n1.next;
temp=temp.next;
}else{
temp.next=n2;
n2=n2.next;
temp=temp.next;
}
}
while(n1!=null){
temp.next=n1;
n1=n1.next;
temp=temp.next;
}
while(n2!=null){
temp.next=n2;
n2=n2.next;
temp=temp.next;
}
return head;
}
}