【LeetCode】 023. Merge k Sorted Lists

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

/**
 * 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.length == 0) {
            return null;
        }
        PriorityQueue list = new PriorityQueue(new Comparator() {
            @Override
            public int compare(ListNode n1, ListNode n2) {
                return n1.val - n2.val;
            }
        });
        ListNode temp = new ListNode(0);
        ListNode res = temp;
        for (ListNode subList : lists) {
            if (subList != null) {
                list.add(subList);
            }
        }
        while (!list.isEmpty()) {
            temp.next = list.poll();
            temp = temp.next;
            if (temp.next != null) {
                list.add(temp.next);
            }
        }
        return res.next;
    }
}


你可能感兴趣的:(LeetCode)