思路一:归并
假设K个链表,每个长度为n
- 顺序遍历合并,在第一次合并后,ans 的长度为 n;第二次合并后,ans 的长度为 2×n,第 i 次合并后,ans 的长度为 i×n。总时间复杂度O(k^2 ×n)
- 二分 / 归并,递归
第一轮合并 k/2 组链表,每一组时间复杂度为 O(2n),第二轮合并 k/4 组链表
每一组的时间代价是 O(4n)。总时间复杂度为O(kn×logk)。
class Solution {
public ListNode mergeKLists(ListNode[] lists) {
if(lists.length==0) return null;
return helper(lists,0,lists.length-1);
}
public ListNode helper(ListNode[] lists,int left,int right){
if(left==right) return lists[left];
int mid=(left+right)/2;
ListNode l1=helper(lists,left,mid);
ListNode l2=helper(lists,mid+1,right);
return mergeTwo(l1,l2);
}
public ListNode mergeTwo(ListNode l1,ListNode l2){
ListNode pre=new ListNode();
ListNode p=pre;
while(l1!=null && l2!=null){
if(l1.val<l2.val){
p.next=l1;
l1=l1.next;
}else{
p.next=l2;
l2=l2.next;
}
p=p.next;
}
p.next= l1==null?l2:l1;
return pre.next;
}
}
思路二:堆排序/优先队列
类似两两合并的操作,先从 k 个链表中找出最小的,安在新链表上,指针后移,将这个最小的节点的next入队,重新排序,接着选最小的
class Solution {
public ListNode mergeKLists(ListNode[] lists) {
if (lists == null || lists.length == 0) return null;
PriorityQueue<ListNode> queue = new PriorityQueue<>(lists.length, new Comparator<ListNode>() {
@Override
public int compare(ListNode o1, ListNode o2) {
if (o1.val < o2.val) return -1;
else if (o1.val == o2.val) return 0;
else return 1;
}
});
ListNode dummy = new ListNode(0);
ListNode p = dummy;
for (ListNode node : lists) {
if (node != null) queue.add(node);
}
while (!queue.isEmpty()) {
p.next = queue.poll();
p = p.next;
if (p.next != null) queue.add(p.next);
}
return dummy.next;
}
}