feat: add top_k.c and refactor top_k.js (#889)

* Add top_k.c based on my_heap.c

* Improve the implementation of top_k.js

* Add a comment to top_k
This commit is contained in:
Yudong Jin
2023-10-26 02:54:19 +08:00
committed by GitHub
parent 9f4076d1c1
commit 7822bf9cd4
13 changed files with 190 additions and 73 deletions
+24 -22
View File
@@ -123,33 +123,35 @@ class MaxHeap {
}
/* Driver Code */
/* 初始化大顶堆 */
const maxHeap = new MaxHeap([9, 8, 6, 6, 7, 5, 2, 1, 4, 3, 6, 2]);
console.log('\n输入列表并建堆后');
maxHeap.print();
if (require.main === module) {
/* 初始化大顶堆 */
const maxHeap = new MaxHeap([9, 8, 6, 6, 7, 5, 2, 1, 4, 3, 6, 2]);
console.log('\n输入列表并建堆后');
maxHeap.print();
/* 获取堆顶元素 */
let peek = maxHeap.peek();
console.log(`\n堆顶元素为 ${peek}`);
/* 获取堆顶元素 */
let peek = maxHeap.peek();
console.log(`\n堆顶元素为 ${peek}`);
/* 元素入堆 */
let val = 7;
maxHeap.push(val);
console.log(`\n元素 ${val} 入堆后`);
maxHeap.print();
/* 元素入堆 */
let val = 7;
maxHeap.push(val);
console.log(`\n元素 ${val} 入堆后`);
maxHeap.print();
/* 堆顶元素出堆 */
peek = maxHeap.pop();
console.log(`\n堆顶元素 ${peek} 出堆后`);
maxHeap.print();
/* 堆顶元素出堆 */
peek = maxHeap.pop();
console.log(`\n堆顶元素 ${peek} 出堆后`);
maxHeap.print();
/* 获取堆大小 */
let size = maxHeap.size();
console.log(`\n堆元素数量为 ${size}`);
/* 获取堆大小 */
let size = maxHeap.size();
console.log(`\n堆元素数量为 ${size}`);
/* 判断堆是否为空 */
let isEmpty = maxHeap.isEmpty();
console.log(`\n堆是否为空 ${isEmpty}`);
/* 判断堆是否为空 */
let isEmpty = maxHeap.isEmpty();
console.log(`\n堆是否为空 ${isEmpty}`);
}
module.exports = {
MaxHeap,