题目描述:
合并 k 个排序链表,返回合并后的排序链表。请分析和描述算法的复杂度。
**示例:
输入:
[
1->4->5,
1->3->4,
2->6
]
输出: 1->1->2->3->4->4->5->6
算法实现:
JavaScript
递归暴力法
/**
* 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 merge2Lists(lists[0], lists[1])
default:
let mid = Math.round(lists.length / 2)
return merge2Lists(mergeKLists(lists.slice(0, mid)),
mergeKLists(lists.slice(mid, lists.length)))
}
};
function merge2Lists (l1, l2) {
var listToArray = (list) => {
if(list == null) {
return []
} else if(list.next) {
return [list.val, ...listToArray(list.next)]
} else {
return [list.val]
}
}
var arrSort = (arr) => {
arr.sort((a, b) => a - b)
return arr
}
var arrayToList = (arr) => {
if(arr.length > 0) {
let node = new ListNode(arr.shift())
node.next = arrayToList(arr)
return node
} else {
return null
}
}
return arrayToList(arrSort([...listToArray(l1),...listToArray(l2)]))
}
递归法
/**
* 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 merge2Lists(lists[0], lists[1])
default:
let mid = Math.round(lists.length / 2)
return merge2Lists(mergeKLists(lists.slice(0, mid)),
mergeKLists(lists.slice(mid, lists.length)))
}
};
function merge2Lists (l1, l2) {
if(l1 === null){
return l2
}
if(l2 === null){
return l1
}
if(l1.val < l2.val){
l1.next = merge2Lists(l1.next, l2)
return l1
}else{
l2.next = merge2Lists(l1, l2.next)
return l2
}
}
思考:
总结:
在实现递归的过程中遇到了很多的困难,改bug改了四五个小时,最终也没有通过自己的想法实现,最后借鉴了别人的代码,勉强通过了。