c++
class Solution {
public:
struct CMP {
bool operator()(ListNode *q, ListNode *p) {
return q->val > p->val;
}
};
ListNode* mergeKLists(vector<ListNode*>& lists) {
priority_queue<ListNode *, vector<ListNode *>, CMP> que;
ListNode head(0);
ListNode *headp = &head;
for (auto x : lists) {
if (x == nullptr) continue;
que.push(x);
}
while (!que.empty()) {
ListNode *tmp = que.top();
que.pop();
headp->next = tmp;
headp = tmp;
if (tmp->next) que.push(tmp->next);
}
return head.next;
}
};
js
class MinHeap {
constructor() {
this.heap = [];
}
swap(i1, i2) {
[this.heap[i1], this.heap[i2]] = [this.heap[i2], this.heap[i1]];
}
getParentIndex(i) {
return (i - 1) >> 1;
}
getleftIndex(i) {
return 2 * i + 1;
}
getrightIndex(i) {
return 2 * i + 2;
}
shiftUp(index) {
if (index === 0) return;
const parentIndex = this.getParentIndex(index);
if (this.heap[parentIndex] && this.heap[parentIndex].val > this.heap[index].val) {
this.swap(parentIndex, index);
this.shiftUp(parentIndex);
}
}
shiftDown(index) {
const leftIndex = this.getleftIndex(index);
const rightIndex = this.getrightIndex(index);
if (this.heap[leftIndex] && this.heap[leftIndex].val < this.heap[index].val) {
this.swap(leftIndex, index);
this.shiftDown(leftIndex);
}
if (this.heap[rightIndex] && this.heap[rightIndex].val < this.heap[index].val) {
this.swap(rightIndex, index);
this.shiftDown(rightIndex);
}
}
insert(value) {
this.heap.push(value);
this.shiftUp(this.heap.length - 1);
}
pop() {
if(this.size() === 1) return this.heap.shift()
const top = this.heap[0]
this.heap[0] = this.heap.pop();
this.shiftDown(0);
return top
}
peek() {
return this.heap[0];
}
// 获取堆的大小
size() {
return this.heap.length;
}
}
var mergeKLists = function(lists) {
var heap = new MinHeap();
var ans = new ListNode(), p = ans;
for (var x of lists) {
if (!x) continue;
heap.insert(x);
}
while (heap.size()) {
var tmp = heap.pop();
p.next = tmp;
p = tmp;
if (tmp.next) heap.insert(tmp.next);
}
return ans.next;
};