【Leetcode】23. Merge k Sorted Lists

Question:

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

Tips:

将k个有序的链表合并成为一个有序链表。

思路:

这个题目是将两个链表合并为一个有序链表的升级版本。我的思想还是,两个两个的合并。每次只合并两个链表。

代码:

public ListNode mergeKLists(ListNode[] lists) {
        if (lists.length == 0)
            return null;
        if (lists.length == 1)
            return lists[0];
        return partion(lists, 0, lists.length - 1);
    }

    // 将ListNode数组两两分为一组,调用merge函数
    private ListNode partion(ListNode[] lists, int i, int j) {
        if (i == j)
            return lists[i];
        if (i < j) {
            int temp = (i + j) / 2;
            ListNode l1 = partion(lists, i, temp);
            ListNode l2 = partion(lists, temp + 1, j);
            return merge(l1, l2);
        } else {
            return null;
        }
    }

    // 合并两个链表
    private ListNode merge(ListNode l1, ListNode l2) {
        if (l1 == null)
            return l2;
        if (l2 == null)
            return l1;
        ListNode dummy = new ListNode(-1);
        ListNode head = dummy;
        while (l1 != null && l2 != null) {
            if (l1.val <= l2.val) {
                dummy.next = l1;
                l1 = l1.next;
            } else {
                dummy.next = l2;
                l2 = l2.next;
            }
            dummy = dummy.next;
        }
        while (l1 != null) {
            dummy.next = l1;
            l1 = l1.next;
            dummy = dummy.next;
        }
        while (l2 != null) {
            dummy.next = l2;
            l2 = l2.next;
            dummy = dummy.next;
        }

        return head.next;
    }

 

posted @ 2018-03-05 10:13  于淼  阅读(91)  评论(0编辑  收藏  举报