题目描述:
合并 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}
*/
var mergeKLists = function(lists) {
var array=[];var res=new ListNode(0);
var list=res;
if(!lists || lists.length == 0) return null;
lists.forEach(item=>{
while(item){
array.push(item.val);
item=item.next;
}
})
array.sort((a,b)=>a-b).forEach(item=>{
var tmp=new ListNode();
tmp.val=item;
list.next=tmp;
list=list.next;
});
return res.next;
};