关于代码报错的问题
来源:10-5 LeetCode:23. 合并K个排序链表

谦瑞
2022-03-29
class MinHeap {
constructor() {
this.heap = [];
}
swap(i1, i2) {
const temp = this.heap[i1];
this.heap[i1] = this.heap[i2];
this.heap[i2] = temp;
}
getParentIndex(i) {
return (i - 1) >> 1;
}
getLeftIndex(i) {
return i * 2 + 1;
}
getRightIndex(i) {
return i * 2 + 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] < this.heap[index]) {
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;
}
}
/**
- 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) {
const res = new ListNode(0);
let p = res;
const h = new MinHeap();
lists.forEach(l =>{
if(l) h.insert(l);
});
while(h.size()){
const n = h.pop();
p.next = n;
p = p.next;
if(n.next) h.insert(n.next);
}
return res.next;
};
老师您看下,这是所有的代码
写回答
3回答
-
你先跟课程的代码对比一下呢,我们课程提供了代码的。
00 -
weixin_慕用7109063
2022-11-30
粗略看了一下,if (this.heap[rightIndex] && this.heap[rightIndex] < this.heap[index]) 这一行对比的时候没有取val属性的值来对比
00 -
lewis
2022-03-29
你这个miniheap是自己手动写的还是从代码仓库里拷贝的?我建议你先拷贝课程的代码,先通过提交。然后再自己手动写。
012022-03-29
相似问题