首页 > 其他分享 >23. Merge k Sorted Lists[Hard]

23. Merge k Sorted Lists[Hard]

时间:2023-02-01 10:44:43浏览次数:43  
标签:head ListNode Hard lists next Merge result node1 Sorted

23. Merge k Sorted Lists

You are given an array of k linked-lists lists, each linked-list is sorted in ascending order.

Merge all the linked-lists into one sorted linked-list and return it.

Constraints:

  • k == lists.length
  • 0 <= k <= 10^4
  • 0 <= lists[i].length <= 500
  • -10^4 <= lists[i][j] <= 10^4
  • lists[i] is sorted in ascending order.
  • The sum of lists[i].length will not exceed 104.

Example

Input: lists = [[1,4,5],[1,3,4],[2,6]]
Output: [1,1,2,3,4,4,5,6]
Explanation: The linked-lists are:
[
  1->4->5,
  1->3->4,
  2->6
]
merging them into one sorted list:
1->1->2->3->4->4->5->6

题解

    public ListNode mergeKLists(ListNode[] lists) {
        // 相当于是N个双链表合并
        if (lists.length == 0)
            return null;
        // 把首位链表作为结果
        ListNode result = lists[0];
        for (int i = 1; i < lists.length; i++) {
            // 和数组中每一个链表做合并得到最后结果
            result = mergeTwoList(result, lists[i]);
        }

        return result;
    }

    // 双链表合并
    public ListNode mergeTwoList(ListNode node1, ListNode node2) {
        ListNode result, head;
        result = head = new ListNode();

        while (node1 != null && node2 != null) {
            if (node1.val > node2.val) {
                head.next = new ListNode(node2.val, new ListNode());
                node2 = node2.next;
            } else {
                head.next = new ListNode(node1.val, new ListNode());
                node1 = node1.next;
            }
            head = head.next;
        }

        if (node1 == null)
            head.next = node2;
        else
            head.next = node1;

        return result.next;
    }

标签:head,ListNode,Hard,lists,next,Merge,result,node1,Sorted
From: https://www.cnblogs.com/tanhaoo/p/17081777.html

相关文章