合并 k 个排序链表,返回合并后的排序链表。请分析和描述算法的复杂度。
示例:
输入:
[
1->4->5,
1->3->4,
2->6
]
输出: 1->1->2->3->4->4->5->6
思路:
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode[]} lists
* @return {ListNode}
*/
const mergeKLists = lists => {
const merge2Lists = (l1, l2) => {
if (!l1 && l2) return l2;
if (l1 && !l2) return l1;
let head = new ListNode(null);
const result = head;
while (l1 && l2) {
if (l1.val <= l2.val) {
head.next = l1;
l1 = l1.next;
} else {
head.next = l2;
l2 = l2.next;
}
head = head.next;
}
let left = l1 || l2;
while (left) {
head.next = left;
head = head.next;
left = left.next;
}
return result.next;
};
while (lists.length > 1) {
const tmp = [];
for (let i = 0; i < lists.length / 2; ++i) {
tmp.push(merge2Lists(lists[i * 2], lists[i * 2 + 1]));
}
lists = tmp;
}
return lists[0] || null;
};