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
思路:
将list中的n个元素添加进从小到大排序的优先队
此时从队列中获取的就是最小值的ListNode.
当队列不为空时,循环从队列中取出元素,添加到结果集中,并将取出的ListNode的下一个ListNode添加到队列中
假设lists中有n个元素,每个listnode的长度为k
时间复杂度为O(nlogk)
/**
* 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>heap=new PriorityQueue(lists.length,new Comparator<ListNode>(){
public int compare(ListNode o1,ListNode o2){
return o1.val-o2.val;
}
});
ListNode dummyHead=new ListNode(-1);
ListNode cur=dummyHead;
for(ListNode node:lists)
if(node!=null)
heap.add(node);
while(!heap.isEmpty()){
cur.next=heap.poll();
cur=cur.next;
if(cur.next!=null)
heap.add(cur.next);
}
return dummyHead.next;
}
}