Description
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
Example:
Input:
[
1->4->5,
1->3->4,
2->6
]
Output: 1->1->2->3->4->4->5->6
Solution
将k个已排序的链表再次排序输出为一整条。
We use a priority queue to sort each node. Overide a new Comparator<ListNode> for this problem, which put node with smaller value in front of bigger one.
Then use a node tail to label tail of result list. When a new node is polled from pq, it becomes tail and if it has more nodes behind, put tail’s next in to pq as well.
Code
/**
* 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.length == 0){
return null;
}
PriorityQueue<ListNode> pq = new PriorityQueue<ListNode>(lists.length, new Comparator<ListNode>(){
@Override
public int compare(ListNode l1, ListNode l2){
if (l1.val < l2.val){
return -1;
}
else if (l1.val == l2.val){
return 0;
}
else{
return 1;
}
}
});
ListNode dummy = new ListNode(0);
ListNode tail = dummy;
for (ListNode node : lists){
if (node != null){
pq.add(node);
}
}
while(!pq.isEmpty()){
tail.next = pq.poll();
tail = tail.next;
if(tail.next != null){
pq.add(tail.next);
}
}
return dummy.next;
}
}
Time Complexity: O(nlogk)
Space Complexity: O(k)
Review
A recursion approach.
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;
}
}