给你一个链表数组,每个链表都已经按升序排列。

    请你将所有链表合并到一个升序链表中,返回合并后的链表。

    示例 1:

    输入:lists = [[1,4,5],[1,3,4],[2,6]]
    输出:[1,1,2,3,4,4,5,6]
    解释:链表数组如下:
    [
    1->4->5,
    1->3->4,
    2->6
    ]
    将它们合并到一个有序链表中得到。
    1->1->2->3->4->4->5->6
    示例 2:

    输入:lists = []
    输出:[]
    示例 3:

    输入:lists = [[]]
    输出:[]

    提示:

    k == lists.length
    0 <= k <= 10^4
    0 <= lists[i].length <= 500
    -10^4 <= lists[i][j] <= 10^4
    lists[i] 按 升序 排列
    lists[i].length 的总和不超过 10^4


    1. /**
    2. * Definition for singly-linked list.
    3. * public class ListNode {
    4. * int val;
    5. * ListNode next;
    6. * ListNode() {}
    7. * ListNode(int val) { this.val = val; }
    8. * ListNode(int val, ListNode next) { this.val = val; this.next = next; }
    9. * }
    10. */
    11. class Solution {
    12. public ListNode mergeKLists(ListNode[] lists) {
    13. PriorityQueue<ListNode> q = new PriorityQueue<>((a,b) -> a.val-b.val);
    14. for (ListNode list : lists) {
    15. if (list != null)
    16. q.add(list);
    17. }
    18. ListNode dummy = new ListNode(0);
    19. ListNode cur = dummy;
    20. while (!q.isEmpty()) {
    21. ListNode minNode = q.poll();
    22. cur.next = minNode;
    23. cur = cur.next;
    24. if (minNode.next != null) {
    25. q.add(minNode.next);
    26. }
    27. }
    28. return dummy.next;
    29. }
    30. }

    分治

    1. /**
    2. * Definition for singly-linked list.
    3. * public class ListNode {
    4. * int val;
    5. * ListNode next;
    6. * ListNode() {}
    7. * ListNode(int val) { this.val = val; }
    8. * ListNode(int val, ListNode next) { this.val = val; this.next = next; }
    9. * }
    10. */
    11. class Solution {
    12. public ListNode mergeKLists(ListNode[] lists) {
    13. if (lists.length == 0 || lists == null) return null;
    14. return merge(lists, 0, lists.length - 1);
    15. }
    16. private ListNode merge(ListNode[] lists, int l, int r) {
    17. if (l == r) return lists[l];
    18. int mid = l + r >> 1;
    19. ListNode l1 = merge(lists, l, mid);
    20. ListNode l2 = merge(lists, mid + 1, r);
    21. return mergeTwoLists(l1, l2);
    22. }
    23. private ListNode mergeTwoLists(ListNode l1, ListNode l2) {
    24. if (l1 == null || l2 == null)
    25. return l1 == null ? l2 : l1;
    26. if (l1.val <= l2.val) {
    27. l1.next = mergeTwoLists(l1.next, l2);
    28. return l1;
    29. } else {
    30. l2.next = mergeTwoLists(l2.next, l1);
    31. return l2;
    32. }
    33. }
    34. }