Q: Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
分析:有人提到用败者树或胜者树实现。其实,完全可以借鉴现有常规的数据结构PriorityQueue,实现类似的功能。PriorityQueue实现原理是维护一个最小堆,该数据结构非常常用,以至于java中有现成的库。
思路:1.取出k个链表的头结点,构造一个最小堆。2.输出堆顶节点,插入堆顶节点关联的下一个链表节点。时间复杂度O(n*logk)
public class Solution {
public ListNode mergeKLists(ArrayList<ListNode> lists) {
if(lists==null || lists.size()==0) return null;
PriorityQueue<ListNode> pq=new PriorityQueue<ListNode>(lists.size(),new Comparator<Object>(){
public int compare(Object o1, Object o2) {
ListNode a=(ListNode)o1;
ListNode b=(ListNode)o2;
return a.val-b.val;
}
});
for(ListNode node : lists)
{
if(node!=null)
pq.add(node);
}
ListNode head=new ListNode(-1);
ListNode p=head;
while(!pq.isEmpty())
{
ListNode node=pq.poll();
p.next=node;
p=p.next;
if(node.next!=null){
pq.add(node.next);
}
}
return head.next;
}
}