Open Ray-56 opened 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;
}
23. 合并K个升序链表
给你一个链表数组,每个链表都已经按升序排列。
请你将所有链表合并到一个升序链表中,返回合并后的链表。
示例 1:
示例 2:
示例 3:
注意: