23. Merge k Sorted Lists

Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.

归并排序o(nlgk);

/** heap
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode mergeKLists(ListNode[] lists) {
        if (lists == null || lists.length == 0)
            return null;
        else if (lists.length == 1)
            return lists[0];
        return divide(lists, 0, lists.length - 1); 
    }

    private ListNode divide(ListNode[] lists, int begin, int end) {
        if (end <= begin)
            return lists[begin];
        int middle = (begin + end) / 2;
        ListNode left = divide(lists, begin, middle);
        ListNode right = divide(lists, middle + 1, end);
        return mergeTwoList(left, right);
    }
    public ListNode mergeTwoList(ListNode l1, ListNode l2){
        if(l1 == null)
            return l2;
        if(l2 == null)
            return l1;
        if(l1.val < l2.val){
            l1.next = mergeTwoList(l1.next , l2);
            return l1;
        }
        else{
            l2.next = mergeTwoList(l1 ,l2.next);
            return l2;            
        }
    }
}

法二 : 优先队列

维护一个长为n的队列  o(n *lgk)

public ListNode mergeKLists(ListNode[] lists) {
        PriorityQueue<ListNode> queue = new PriorityQueue<ListNode>(new Comparator<ListNode>(){
              public int compare(ListNode l1, ListNode l2){
                  return l1.val - l2.val;
              }
            });
        for(ListNode n: lists){
            if(n != null)
                queue.offer(n);
        }
        ListNode dummy = new ListNode(0);
        ListNode tail = dummy;
        while(!queue.isEmpty()){
            ListNode ln = queue.poll();
            tail.next = ln;
            tail = tail.next;
            if(ln != null && ln.next != null)
                queue.add(ln.next);
        }
        return dummy.next;
    }
原文地址:https://www.cnblogs.com/joannacode/p/6012357.html