题目描述:
合并 k 个排序链表,返回合并后的排序链表。请分析和描述算法的复杂度。
示例:
输入:
[
1->4->5,
1->3->4,
2->6
]
输出: 1->1->2->3->4->4->5->6
代码实现:
- 递归逐一合并,前面我们已经做了合并两个有序链表,现在通过递归,把所有链表拆分逐一合并即可。
- 时间复杂度:O(kn)
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode[]} lists
* @return {ListNode}
*/
var mergeKLists = function(lists) {
switch(lists.length) {
case 0:
return null
case 1:
return lists[0]
case 2:
return mergeTwoLists(lists[0], lists[1])
default:
let mid = Math.round(lists.length / 2)
return mergeTwoLists(mergeKLists(lists.slice(0, mid)),
mergeKLists(lists.slice(mid, lists.length)))
}
};
function mergeTwoLists (l1, 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
}
};