Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
K路合并,O(NK)版本,每路一个指针,每轮找到最小值,推进相应位置指针。
类似于
373. Find K Pairs with Smallest Sums
http://blog.youkuaiyun.com/wdlsjdl2/article/details/51913760
这里懒得写了,贴一个
http://blog.youkuaiyun.com/beiyetengqing/article/details/7685593
public class Solution {
public ListNode mergeKLists(ArrayList<ListNode> lists) {
ListNode head = null;
ListNode current = null;
boolean isAllNull = false;
while (!isAllNull) {
isAllNull = true;
ListNode min = null;
int position = -1;
for (int i = 0; i < lists.size(); i++) {
if (min == null && lists.get(i) != null) {
min = lists.get(i);
isAllNull = false;
position = i;
} else if (lists.get(i) != null){
isAllNull = false;
if (min.val > lists.get(i).val) {
min = lists.get(i);
position = i;
}
}
}
if (head == null) {
head = min;
current = min;
} else {
current.next = min;
current = current.next;
}
if (position != -1) {
lists.set(position, lists.get(position).next);
}
}
return head;
}
}
O(NlogK)版本的,使用优先队列库函数
https://discuss.leetcode.com/topic/2780/a-java-solution-based-on-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;
}
}
------------------------------------------------------------------------------------------------------------------------------
O(NlogK)版本的,参考《algroithms》第四版,代码非本题,只是阐述类似思想。