原题:
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
此题可以递归的两两归并,也可以使用优先级队列
代码:
public ListNode mergeKLists(List<ListNode> lists) {
if(lists==null || lists.size()<1) {
return null;
}
ListNode head = new ListNode(0);
ListNode pHead = head;
PriorityQueue<ListNode> pQueue = new PriorityQueue<ListNode>(lists.size(), new Comparator<ListNode>() {
@Override
public int compare(ListNode node1, ListNode node2) {
return node1.val - node2.val;
}
});
for(int i=0; i<lists.size(); i++) {
ListNode node = lists.get(i);
if(node != null) {
pQueue.add(node);
}
}
while(!pQueue.isEmpty()) {
pHead.next = pQueue.poll();
pHead = pHead.next;
if(pHead.next != null) {
pQueue.add(pHead.next);
}
}
return head.next;
}