Merge k Sorted Lists

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

Tips:

建个堆,哪个小往里压

Code:

/**
 * 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;
        }
        ListNode result = new ListNode(0);
        ListNode copy = result;
        Queue<ListNode> queue = new PriorityQueue<>(lists.length, new Comparator<ListNode>() {
            public int compare(ListNode a, ListNode b) {
                if (a == null) {
                    return 1;
                }
                else if (b == null) {
                    return -1;
                }
                else return a.val - b.val;
            }
        });
        for (int i = 0; i < lists.length; i++) {
            if (lists[i] != null) {
                queue.add(lists[i]);                
            }
        }
        while (!queue.isEmpty()) {
            ListNode temp = queue.poll();
            result.next = new ListNode(temp.val);
            result = result.next;
            if (temp.next != null) {
                queue.add(temp.next);
            }
        }
        return copy.next;
    }
}

results matching ""

    No results matching ""