标签:divide and conquer priorityqueue
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
分支策略:每次归并两个已排好序的链表,直至只剩下一个链表。
public class Solution {
public ListNode mergeKLists(List<ListNode> lists) {
//处理特殊情况
if (lists == null)
return null;
int length = lists.size();
if (length == 0)
return null;
if (length == 1)
return lists.get(0);
//
ListNode low, high;
while (length != 1){//逐个归并有序串
int index;
for (index = 0; index < length/2; ++index){
low = lists.get(2*index);
high = lists.get(2*index+1);
lists.set(index, merge2Lists(low, high));
}
if (length%2 == 1)
lists.set(index, lists.get(length-1));
length = (length + 1) / 2;
}
return lists.get(0);
}
public ListNode merge2Lists(ListNode low, ListNode high){
ListNode result = new ListNode(-1);
ListNode p = result;
while (low != null && high != null){
if (low.val < high.val){
p.next = low;
low = low.next;
p = p.next;
} else {
p.next = high;
high = high.next;
p = p.next;
}
}
if (low == null)
p.next = high;
else
p.next = low;
return result.next;
}
}public class Solution {
//此段代码出自https://oj.leetcode.com/discuss/25518/13-lines-in-java
public ListNode mergeKLists(List<ListNode> lists) {
Queue<ListNode> heap = new PriorityQueue(new Comparator<ListNode>(){
@Override public int compare(ListNode l1, ListNode l2) {
return l1.val - l2.val;
}
});
ListNode head = new ListNode(0), tail = head;
for (ListNode node : lists) if (node != null) heap.offer(node);
while (!heap.isEmpty()) {
tail.next = heap.poll();
tail = tail.next;
if (tail.next != null) heap.offer(tail.next);
}
return head.next;
}
}
LeetCode -- Merge k Sorted Lists (Divide and Conquer / PriorityQueue)
标签:divide and conquer priorityqueue
原文地址:http://blog.csdn.net/jdplus/article/details/44085161