mirror of
https://github.com/krahets/hello-algo.git
synced 2026-11-25 21:23:21 +08:00
Retranslate the complete English edition from Simplified Chinese (#2010)
* Retranslate the complete English edition from Simplified Chinese * Polish three English explanations after reader-focused review
This commit is contained in:
@@ -10,27 +10,27 @@ const { printHeap } = require('../modules/PrintUtil');
|
||||
class MaxHeap {
|
||||
#maxHeap;
|
||||
|
||||
/* Constructor, build empty heap or build heap from input list */
|
||||
/* Constructor: create an empty heap or build a heap from the input list */
|
||||
constructor(nums) {
|
||||
// Add list elements to heap as is
|
||||
// Place the list elements in the heap without changing their order
|
||||
this.#maxHeap = nums === undefined ? [] : [...nums];
|
||||
// Heapify all nodes except leaf nodes
|
||||
// Sift down from every non-leaf node
|
||||
for (let i = this.#parent(this.size() - 1); i >= 0; i--) {
|
||||
this.#siftDown(i);
|
||||
}
|
||||
}
|
||||
|
||||
/* Get index of left child node */
|
||||
/* Get the left child index */
|
||||
#left(i) {
|
||||
return 2 * i + 1;
|
||||
}
|
||||
|
||||
/* Get index of right child node */
|
||||
/* Get the right child index */
|
||||
#right(i) {
|
||||
return 2 * i + 2;
|
||||
}
|
||||
|
||||
/* Get index of parent node */
|
||||
/* Get the parent index */
|
||||
#parent(i) {
|
||||
return Math.floor((i - 1) / 2); // Floor division
|
||||
}
|
||||
@@ -42,115 +42,115 @@ class MaxHeap {
|
||||
this.#maxHeap[j] = tmp;
|
||||
}
|
||||
|
||||
/* Get heap size */
|
||||
/* Get the heap size */
|
||||
size() {
|
||||
return this.#maxHeap.length;
|
||||
}
|
||||
|
||||
/* Check if heap is empty */
|
||||
/* Check whether the heap is empty */
|
||||
isEmpty() {
|
||||
return this.size() === 0;
|
||||
}
|
||||
|
||||
/* Access top element */
|
||||
/* Access the top element of the heap */
|
||||
peek() {
|
||||
return this.#maxHeap[0];
|
||||
}
|
||||
|
||||
/* Element enters heap */
|
||||
/* Push an element onto the heap */
|
||||
push(val) {
|
||||
// Add node
|
||||
// Add a node
|
||||
this.#maxHeap.push(val);
|
||||
// Heapify from bottom to top
|
||||
// Sift up
|
||||
this.#siftUp(this.size() - 1);
|
||||
}
|
||||
|
||||
/* Starting from node i, heapify from bottom to top */
|
||||
/* Sift up starting from node i */
|
||||
#siftUp(i) {
|
||||
while (true) {
|
||||
// Get parent node of node i
|
||||
// Get the parent of node i
|
||||
const p = this.#parent(i);
|
||||
// When "crossing root node" or "node needs no repair", end heapify
|
||||
// Stop sifting when the root has been passed or the node needs no repair
|
||||
if (p < 0 || this.#maxHeap[i] <= this.#maxHeap[p]) break;
|
||||
// Swap two nodes
|
||||
// Swap the two nodes
|
||||
this.#swap(i, p);
|
||||
// Loop upward heapify
|
||||
// Continue sifting up
|
||||
i = p;
|
||||
}
|
||||
}
|
||||
|
||||
/* Element exits heap */
|
||||
/* Pop an element from the heap */
|
||||
pop() {
|
||||
// Handle empty case
|
||||
// Handle an empty heap
|
||||
if (this.isEmpty()) throw new Error('Heap is empty');
|
||||
// Delete node
|
||||
// Swap the root with the rightmost leaf on the last level (swap the first and last elements)
|
||||
this.#swap(0, this.size() - 1);
|
||||
// Remove node
|
||||
// Remove a node
|
||||
const val = this.#maxHeap.pop();
|
||||
// Return top element
|
||||
// Sift down
|
||||
this.#siftDown(0);
|
||||
// Return heap top element
|
||||
// Return the top element of the heap
|
||||
return val;
|
||||
}
|
||||
|
||||
/* Starting from node i, heapify from top to bottom */
|
||||
/* Sift down starting from node i */
|
||||
#siftDown(i) {
|
||||
while (true) {
|
||||
// If node i is largest or indices l, r are out of bounds, no need to continue heapify, break
|
||||
// Find the node with the largest value among i, l, and r, and store its index in ma
|
||||
const l = this.#left(i),
|
||||
r = this.#right(i);
|
||||
let ma = i;
|
||||
if (l < this.size() && this.#maxHeap[l] > this.#maxHeap[ma]) ma = l;
|
||||
if (r < this.size() && this.#maxHeap[r] > this.#maxHeap[ma]) ma = r;
|
||||
// Swap two nodes
|
||||
// Stop if node i is largest or both child indices l and r are out of bounds
|
||||
if (ma === i) break;
|
||||
// Swap two nodes
|
||||
// Swap the two nodes
|
||||
this.#swap(i, ma);
|
||||
// Loop downwards heapification
|
||||
// Continue sifting down
|
||||
i = ma;
|
||||
}
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Print the heap (binary tree) */
|
||||
print() {
|
||||
printHeap(this.#maxHeap);
|
||||
}
|
||||
|
||||
/* Extract elements from heap */
|
||||
/* Get the elements in the heap */
|
||||
getMaxHeap() {
|
||||
return this.#maxHeap;
|
||||
}
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
if (require.main === module) {
|
||||
/* Consider negating the elements before entering the heap, which can reverse the size relationship, thus implementing max heap */
|
||||
/* Initialize a max heap */
|
||||
const maxHeap = new MaxHeap([9, 8, 6, 6, 7, 5, 2, 1, 4, 3, 6, 2]);
|
||||
console.log('\nAfter inputting list and building heap');
|
||||
console.log('\nAfter building a heap from the input list:');
|
||||
maxHeap.print();
|
||||
|
||||
/* Check if heap is empty */
|
||||
/* Get the top element of the heap */
|
||||
let peek = maxHeap.peek();
|
||||
console.log(`\nHeap top element is ${peek}`);
|
||||
console.log(`\nHeap top: ${peek}`);
|
||||
|
||||
/* Element enters heap */
|
||||
/* Push an element onto the heap */
|
||||
let val = 7;
|
||||
maxHeap.push(val);
|
||||
console.log(`\nAfter element ${val} pushes to heap`);
|
||||
console.log(`\nAfter pushing ${val} into the heap:`);
|
||||
maxHeap.print();
|
||||
|
||||
/* Time complexity is O(n), not O(nlogn) */
|
||||
/* Pop the top element from the heap */
|
||||
peek = maxHeap.pop();
|
||||
console.log(`\nAfter heap top element ${peek} pops from heap`);
|
||||
console.log(`\nAfter popping the heap top ${peek}:`);
|
||||
maxHeap.print();
|
||||
|
||||
/* Get heap size */
|
||||
/* Get the heap size */
|
||||
let size = maxHeap.size();
|
||||
console.log(`\nHeap size is ${size}`);
|
||||
console.log(`\nNumber of elements in the heap: ${size}`);
|
||||
|
||||
/* Check if heap is empty */
|
||||
/* Check whether the heap is empty */
|
||||
let isEmpty = maxHeap.isEmpty();
|
||||
console.log(`\nIs heap empty ${isEmpty}`);
|
||||
console.log(`\nIs the heap empty? ${isEmpty}`);
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
|
||||
@@ -6,52 +6,52 @@
|
||||
|
||||
const { MaxHeap } = require('./my_heap');
|
||||
|
||||
/* Element enters heap */
|
||||
/* Push an element onto the heap */
|
||||
function pushMinHeap(maxHeap, val) {
|
||||
// Negate element
|
||||
// Negate the value
|
||||
maxHeap.push(-val);
|
||||
}
|
||||
|
||||
/* Element exits heap */
|
||||
/* Pop an element from the heap */
|
||||
function popMinHeap(maxHeap) {
|
||||
// Negate element
|
||||
// Negate the value
|
||||
return -maxHeap.pop();
|
||||
}
|
||||
|
||||
/* Access top element */
|
||||
/* Access the top element of the heap */
|
||||
function peekMinHeap(maxHeap) {
|
||||
// Negate element
|
||||
// Negate the value
|
||||
return -maxHeap.peek();
|
||||
}
|
||||
|
||||
/* Extract elements from heap */
|
||||
/* Get the elements in the heap */
|
||||
function getMinHeap(maxHeap) {
|
||||
// Negate element
|
||||
// Negate the value
|
||||
return maxHeap.getMaxHeap().map((num) => -num);
|
||||
}
|
||||
|
||||
/* Find the largest k elements in array based on heap */
|
||||
/* Use a heap to find the k largest elements in an array */
|
||||
function topKHeap(nums, k) {
|
||||
// Python's heapq module implements min heap by default
|
||||
// Note: We negate all heap elements to simulate min heap using max heap
|
||||
// Initialize a min heap
|
||||
// Note: negate all values in the heap to simulate a min heap with a max heap
|
||||
const maxHeap = new MaxHeap([]);
|
||||
// Enter the first k elements of array into heap
|
||||
// Push the first k array elements onto the heap
|
||||
for (let i = 0; i < k; i++) {
|
||||
pushMinHeap(maxHeap, nums[i]);
|
||||
}
|
||||
// Starting from the (k+1)th element, maintain heap length as k
|
||||
// Starting with element k+1, keep the heap size at k
|
||||
for (let i = k; i < nums.length; i++) {
|
||||
// If current element is greater than top element, top element exits heap, current element enters heap
|
||||
// If the current element is larger than the heap top, pop the top element and push the current element
|
||||
if (nums[i] > peekMinHeap(maxHeap)) {
|
||||
popMinHeap(maxHeap);
|
||||
pushMinHeap(maxHeap, nums[i]);
|
||||
}
|
||||
}
|
||||
// Return elements in heap
|
||||
// Return the elements in the heap
|
||||
return getMinHeap(maxHeap);
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Driver code */
|
||||
const nums = [1, 7, 6, 3, 2];
|
||||
const k = 3;
|
||||
const res = topKHeap(nums, k);
|
||||
|
||||
Reference in New Issue
Block a user