leetcode 23. 合并K个升序链表
问题描述: 给你一个链表数组,每个链表都已经按升序排列。
请你将所有链表合并到一个升序链表中,返回合并后的链表。
示例 1:
输入: lists = [[1,4,5],[1,3,4],[2,6]]
输出: [1,1,2,3,4,4,5,6]
解释: 链表数组如下:
[
1->4->5,
1->3->4,
2->6
]
将它们合并到一个有序链表中得到。
1->1->2->3->4->4->5->6
示例 2:
输入: lists = []
输出: []
示例 3:
输入: lists = [[]]
输出: []
思路: 小顶堆+快速排序
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode[]} lists
* @return {ListNode}
*/
var mergeKLists = function(lists) {
let heap=new Heap((a,b)=>a.val<b.val)
for(let item of lists) {
if(item!==null){
heap.push(item)
}
}
let ret=new ListNode(null),p=ret;
while(heap.data.length){
let temp=heap.pop();
p.next=temp;
if(temp.next){
heap.push(temp.next)
}
p=p.next
}
return ret.next
};
class Heap {
constructor(cmp) {
this.data = [];
this.cmp = cmp;
}
get size() {
return this.data.length;
}
get top() {
return this.data[0];
}
getData() {
return this.data;
}
swap(i, j) {
[this.data[i], this.data[j]] = [this.data[j], this.data[i]];
}
// 向上冒泡
up(i) {
let index=this.data.length-1;
while(index>0){
let p=Math.floor((index-1)/2);
if(p>=0&&this.cmp(this.data[index],this.data[p])){
this.swap(index,p);
index=p;
}else{
break;
}
}
}
// 下沉操作
down(i) {
if(this.data.length<2)return;
let index=0,l=2*index+1,len=this.data.length;
while(l<len){
let r=l+1;
if(r<len&&this.cmp(this.data[r], this.data[l]))l=r;
if(this.cmp(this.data[index], this.data[l]))break;
this.swap(index,l)
index=l;
l=index*2+1;
}
}
push(item) {
this.data.push(item);
this.up();
}
//删除堆顶元素
pop() {
this.swap(0, this.data.length - 1);
const res = this.data.pop();//已删除的元素(原来的堆顶元素)
this.down();
return res;
}
}