题目描述
合并 k 个排序链表,返回合并后的排序链表。请分析和描述算法的复杂度。
示例:
输入:
[
1->4->5,
1->3->4,
2->6
]
输出: 1->1->2->3->4->4->5->6
题目分析
首先按链表的头节点从小到大进行排序,将头节点保存在堆中。然后poll一个next节点,如果next的next节点不为空,则将其offer在堆中。
最后返回dummy.next
插入的时间复杂度 O(logN);
代码
Java代码如下:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode mergeKLists(ListNode[] lists) {
ListNode dummy = new ListNode(0);
ListNode cur = dummy;
PriorityQueue<ListNode> pq =new PriorityQueue<>((ListNode l1,ListNode l2)->(l1.val-l2.val));
for( ListNode list : lists)
{
if(list!=null)
{
pq.offer(list);
}
}
while(!pq.isEmpty())
{
ListNode next=pq.poll();
cur.next=next;
cur=cur.next;
if(next.next!=null)
{
pq.offer(next.next);
}
}
return dummy.next;
}
}