freeCodeCamp/curriculum/challenges/chinese/10-coding-interview-prep/data-structures/remove-an-element-from-a-ma...

134 lines
3.1 KiB
Markdown
Raw Normal View History

---
id: 587d825b367417b2b2512c8b
title: 从最大堆中删除元素
challengeType: 1
videoUrl: ''
dashedName: remove-an-element-from-a-max-heap
---
# --description--
现在我们可以向堆中添加元素让我们看看如何删除元素。删除和插入元素都需要类似的逻辑。在最大堆中您通常需要删除最大值因此这只需要从树的根中提取它。这将破坏我们树的堆属性因此我们必须以某种方式重新建立它。通常对于最大堆这可以通过以下方式完成将堆中的最后一个元素移动到根位置。如果root的子节点大于它则将root与较大值的子节点交换。继续交换直到父级大于两个子级或者到达树中的最后一级。说明向我们的最大堆添加一个名为remove的方法。此方法应返回已添加到最大堆的最大值并将其从堆中删除。它还应该重新排序堆以便保持堆属性。删除元素后堆中剩余的下一个最大元素应该成为根。此处再次添加插入方法。
# --hints--
存在MaxHeap数据结构。
```js
assert(
(function () {
var test = false;
if (typeof MaxHeap !== 'undefined') {
test = new MaxHeap();
}
return typeof test == 'object';
})()
);
```
MaxHeap有一个名为print的方法。
```js
assert(
(function () {
var test = false;
if (typeof MaxHeap !== 'undefined') {
test = new MaxHeap();
} else {
return false;
}
return typeof test.print == 'function';
})()
);
```
MaxHeap有一个名为insert的方法。
```js
assert(
(function () {
var test = false;
if (typeof MaxHeap !== 'undefined') {
test = new MaxHeap();
} else {
return false;
}
return typeof test.insert == 'function';
})()
);
```
MaxHeap有一个名为remove的方法。
```js
assert(
(function () {
var test = false;
if (typeof MaxHeap !== 'undefined') {
test = new MaxHeap();
} else {
return false;
}
return typeof test.remove == 'function';
})()
);
```
remove方法从最大堆中删除最大元素同时保持最大堆属性。
```js
assert(
(function () {
var test = false;
if (typeof MaxHeap !== 'undefined') {
test = new MaxHeap();
} else {
return false;
}
test.insert(30);
test.insert(300);
test.insert(500);
test.insert(10);
let result = [];
result.push(test.remove());
result.push(test.remove());
result.push(test.remove());
result.push(test.remove());
return result.join('') == '5003003010';
})()
);
```
# --seed--
## --seed-contents--
```js
var MaxHeap = function() {
this.heap = [null];
this.insert = (ele) => {
var index = this.heap.length;
var arr = [...this.heap];
arr.push(ele);
while (ele > arr[Math.floor(index / 2)] && index > 1) {
arr[index] = arr[Math.floor(index / 2)];
arr[Math.floor(index / 2)] = ele;
index = arr[Math.floor(index / 2)];
}
this.heap = arr;
}
this.print = () => {
return this.heap.slice(1);
}
// Only change code below this line
// Only change code above this line
};
```
# --solutions--
```js
// solution required
```