Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
Subscribe to see which companies asked this question.解题思路:
要给k个顺序单链表排序,我们熟知合并两个顺序单链表的操作。但是这里是k个,简单的想:先两个合并,再拿合并的和第三个合并,这样子的每次都会重复遍历前一次合并过的链表,这样重复率太高了,不合适。
于是,就想要尽可能的减少重复遍历的数量,这时候就想到用递归不断二分,合并。
//Arrays.copyOfRange 拷贝数组,from指向开始的下标,to表示结束的后一个下标
public static ListNode mergeKLists(ListNode[] lists) {
if (lists.length == 0)
return null;
if (lists.length == 1)
return lists[0];
ListNode left,right;
left = mergeKLists(Arrays.copyOfRange(lists,0,lists.length/2));
right =mergeKLists(Arrays.copyOfRange(lists,lists.length/2,lists.length));
return mergeTwoLists(left,right);
}
public static ListNode mergeTwoLists(ListNode l1,ListNode l2)
{
if (l1 == null)
return l2;
if (l2 == null)
return l1;
if(l1.val < l2.val)
{
l1.next = mergeTwoLists(l1.next,l2);
return l1;
}
else
{
l2.next = mergeTwoLists(l1,l2.next);
return l2;
}
}
If someone understand how priority queue works, then it would be trivial to walk through the codes.
My question: is that possible to solve this question under the same time complexity without implementing the priority queue?
public class Solution {
public ListNode mergeKLists(List<ListNode> lists) {
if (lists==null||lists.size()==0) return null;
PriorityQueue<ListNode> queue= new PriorityQueue<ListNode>(lists.size(),new Comparator<ListNode>(){
@Override
public int compare(ListNode o1,ListNode o2){
if (o1.val<o2.val)
return -1;
else if (o1.val==o2.val)
return 0;
else
return 1;
}
});
ListNode dummy = new ListNode(0);
ListNode tail=dummy;
for (ListNode node:lists)
if (node!=null)
queue.add(node);
while (!queue.isEmpty()){
tail.next=queue.poll();
tail=tail.next;
if (tail.next!=null)
queue.add(tail.next);
}
return dummy.next;
}
}