23. Merge k Sorted Lists - hard

這道題可以利用merge 2 sorted list。想到D&C, K個list可以被二分,分到最后只有2個list的情況。
畫成樹的話,一共有lgK個level, mergeTwoList的時間是O(n),
所以這道題利用Divide and Conquer,和merge2list,running time應該是O(nlgK):

看見有人用priority queue和comparator做。但速度并沒有提升。
下次刷的時候,研究研究那種做法。

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode mergeKLists(ListNode[] lists) {
        int len = lists.length;
        if (lists == null || len == 0)  return null;
        else if (len == 1)  return lists[0];
        else {
            ListNode[] list1 = Arrays.copyOfRange(lists, 0, len/2);
            ListNode[] list2 = Arrays.copyOfRange(lists, len/2, len);
            ListNode l1 = mergeKLists(list1);
            ListNode l2 = mergeKLists(list2);
            ListNode l3 = mergeTwoLists(l1, l2);
            return l3;
        }
    }
    
    private ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        if (l1 == null) return l2;
        if (l2 == null) return l1;
        if (l1.val < l2.val) {
            l1.next = mergeTwoLists(l1.next, l2);
            return l1;
        }
        else {
            l2.next = mergeTwoLists(l1, l2.next);
            return l2;
        }
    }
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容