Ray-56 / like-algorithms

每天一道算法题,突破自己
2 stars 1 forks source link

✅23. 合并K个升序链表 #158

Open Ray-56 opened 4 years ago

Ray-56 commented 4 years ago

23. 合并K个升序链表

给你一个链表数组,每个链表都已经按升序排列。

请你将所有链表合并到一个升序链表中,返回合并后的链表。

示例 1:

输入:lists = [[1,4,5],[1,3,4],[2,6]]
输出:[1,1,2,3,4,4,5,6]
解释:链表数组如下:
[
  1->4->5,
  1->3->4,
  2->6
]
将它们合并到一个有序链表中得到。
1->1->2->3->4->4->5->6

示例 2:

输入:lists = []
输出:[]

示例 3:

输入:lists = [[]]
输出:[]

注意:

Ray-56 commented 4 years ago

分治

/**
 * @param {ListNode[]} lists
 * @return {ListNode}
 */
var mergeKLists = function(lists) {
    if (lists.length === 0) return null;
    if (lists.length === 1) return lists[0];
    if (lists.length === 2) return mergeTwoLists(lists[0], lists[1]);

    const mid = Math.floor(lists.length / 2);
    const l1 = [];
    for (let i = 0; i < mid; i++) {
        l1[i] = lists[i];
    }

    const l2 = [];
    for (let i = mid, j = 0; i < lists.length; i++, j++) {
        l2[j] = lists[i];
    }

    return mergeTwoLists(mergeKLists(l1), mergeKLists(l2));
};

function mergeTwoLists(head1, head2) {
    if (!head1) return head2;
    if (!head2) return head1;

    let head = null;
    if (head1.val < head2.val) {
        head = head1;
        head.next = mergeTwoLists(head1.next, head2);
    } else {
        head = head2;
        head.next = mergeTwoLists(head1, head2.next);
    }
    return head;
}