参考资料:左程云算法课
23. Merge k Sorted Lists
You are given an array of k linked-lists lists, each linked-list is sorted in ascending order.
Merge all the linked-lists into one sorted linked-list and return it.
Example 1:
Input: lists = [[1,4,5],[1,3,4],[2,6]]
Output: [1,1,2,3,4,4,5,6]
Explanation: The linked-lists are:
[
1->4->5,
1->3->4,
2->6
]
merging them into one sorted list:
1->1->2->3->4->4->5->6
Example 2:
Input: lists = []
Output: []
思路:建立一个小根堆,并维护其大小为k。 首先把k个链表的前k个结点加入到小根堆中,然后 从小根堆中弹出结点cur, 加入cur所在链表的下一个结点,这样我们能保证小根堆大小为k, 直至最后所有结点都被排序。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public class NodeComparator implements Comparator<ListNode>{
@Override
public int compare(ListNode o1,ListNode o2){
return o1.val-o2.val;
}
}
public ListNode mergeKLists(ListNode[] lists) {
if(lists==null || lists.length==0){
return null;
}
int k=lists.length;
PriorityQueue<ListNode> heap = new PriorityQueue<>(new NodeComparator());
for(int i=0;i<k;i++){
if(lists[i]!=null){
heap.add(lists[i]);
}
}
if(heap.isEmpty()){
return null;
}
ListNode head = heap.poll();
ListNode pre = head;
if(pre.next!=null){
heap.add(pre.next);
}
while(!heap.isEmpty()){
ListNode cur = heap.poll();
pre.next = cur;
pre = cur;
if(cur.next!=null){
heap.add(cur.next);
}
}
return head;
}
// 上面是老师写的,下面是自己写的
public ListNode mergeKLists1(ListNode[] lists) {
if(lists==null || lists.length==0)
{
return null;
}
int k= lists.length;
ListNode head=null;
ListNode cur=null;
ListNode pre=null;
PriorityQueue<ListNode> heap= new PriorityQueue<>(new NodeComparator());
for(int i=0;i<k;i++){
if(lists[i]!=null){
heap.add(lists[i]);
}
}
while(!heap.isEmpty()){
cur = heap.poll();
if(head==null){
head=new ListNode(cur.val);
pre = head;
}else{
pre.next = new ListNode(cur.val);
pre = pre.next;
}
if(cur.next!=null){
heap.add(cur.next);
}
}
return head;
}
}