【Leetcode】23. Merge k Sorted Lists

於淼發表於2018-03-05

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;
    }

 

相關文章