23. Merge k Sorted Lists 「合并 K 个排序链表」

合并 k 个已排序链表,并返回一个同样排好序的链表。分析并描述算法复杂度。

举例:
输入: [1->4->5, 1->3->4, 2->6]
输出: 1->1->2->3->4->4->5->6

/*
 * 23. Merge k Sorted Lists
 * https://leetcode.com/problems/merge-k-sorted-lists/
 * https://www.whosneo.com/23-merge-k-sorted-lists/
 */

public class MergeKLists {
    public static void main(String[] args) {
        ListNode head1 = new ListNode(1);
        head1.next = new ListNode(4);
        head1.next.next = new ListNode(5);
        ListNode head2 = new ListNode(1);
        head2.next = new ListNode(3);
        head2.next.next = new ListNode(4);
        ListNode head3 = new ListNode(2);
        head3.next = new ListNode(6);

        ListNode[] lists = new ListNode[]{head1, head2, head3};

        MergeKLists solution = new MergeKLists();
        ListNode node = solution.mergeKLists(lists);
        solution.print(node);
    }

    private void print(ListNode node) {
        for (; node != null; node = node.next) {
            System.out.print(node.val);
            System.out.print("->");
        }
        System.out.println("null");
    }

    private ListNode mergeKLists(ListNode[] lists) {
        int length = lists.length;
        if (length == 0)
            return null;

        for (int interval = 1; interval < length; interval *= 2)
            for (int i = 0; i < length - interval; i += interval * 2)
                lists[i] = mergeTwoLists(lists[i], lists[i + interval]);

        return lists[0];
    }

    private ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        ListNode prev = new ListNode(0);
        ListNode node = prev;
        while (l1 != null && l2 != null) {
            if (l1.val < l2.val) {
                node.next = l1;
                l1 = l1.next;
            } else {
                node.next = l2;
                l2 = l2.next;
            }
            node = node.next;
        }
        node.next = l1 != null ? l1 : l2;
        return prev.next;
    }
}

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注