data-structures - 在我的二进制堆/优先级队列实现中实现删除时遇到问题
问题描述
我正在尝试为我的二进制堆实现实现删除方法。
class Node {
constructor(priority) {
this.priority = priority;
}
}
class PriorityQueue {
constructor() {
this.heap = [null];
}
remove() {
const toRemove = this.heap[1];
this.heap[1] = this.heap.pop();
let currentIdx = 1;
let [left, right] = [2*currentIdx, 2*currentIdx + 1];
let currentChildIdx = this.heap[right] && this.heap[right].priority >= this.heap[left].priority ? right : left; //Assess which child node has higher priority
while (this.heap[currentChildIdx] && this.heap[currentIdx].priority <= this.heap[currentChildIdx].priority) {
let currentNode = this.heap[currentIdx]
let currentChildNode = this.heap[currentChildIdx];
this.heap[currentChildIdx] = currentNode;
this.heap[currentIdx] = currentChildNode;
currentIdx = this.heap.indexOf(currentNode);
}
return toRemove;
}
}
但是,我不确定在运行 while 循环时如何正确更新 currentIdx 和 currentChildIdx 的值。事实上,当我尝试更新 currentIdx 的值时,代码似乎停止工作
currentIdx = this.heap.indexOf(currentNode);
关于我做错了什么的任何提示?
解决方案
在循环中,一旦你交换了 and 的值currentIdx
,currentChildIdx
那么你应该分配currentIdx = currentChildIdx
.
而一旦你改变currentIdx
了,你需要重新计算左右子索引和一个新的currentChildIdx
.
基本思想是:
while currentIdx < heap_length
currentChildIdx = index of largest child
if (heap[currentIdx] >= heap[currentChildIdx])
break; // node is now in the right place
swap(heapCurrentIdx, heap[currentChildIdx)
currentIdx = currentChildIdx
我的建议是您构建该基本结构,然后在调试器中单步执行它以确保它按预期工作。
推荐阅读
- import - 导入 MapiMessage 会给出 KeyError: 'aspose.email'
- python-3.x - multiprocessing.Pool.map 函数在全局命名空间中看不到变量
- javascript - jQuery 选择器找不到我的
- c - 在 C 中存储带有 args 的函数指针
- javascript - 为什么 jQuery 不能在 iframe 之间正确切换?
- python - 编写函数以查找列表中的最长路径(可能是递归?)
- r - 根据 r 中的另一个变量生成标记变量
- ruby-on-rails - 使用带有 Rails 的 jBuilder Elasticsearch 动态设置密钥
- python - Python 3.4 子进程 FileNotFoundError WinError 2
- python - 将 base64 编码图像嵌入 Dash 数据表