mirror of
https://github.com/krahets/hello-algo.git
synced 2025-11-02 04:31:55 +08:00
Add JavaScript and TypeScript code of top_k and update some code style (#686)
* Update JS and TS code style * Add JavaScript and TypeScript code of top_k * Update top_k.ts * Apply suggestions from code review Co-authored-by: Justin Tse <xiefahit@gmail.com> * Apply suggestions from code review Co-authored-by: Justin Tse <xiefahit@gmail.com> --------- Co-authored-by: Yudong Jin <krahets@163.com>
This commit is contained in:
@ -115,6 +115,11 @@ class MaxHeap {
|
||||
print() {
|
||||
printHeap(this.#maxHeap);
|
||||
}
|
||||
|
||||
/* 取出堆中元素 */
|
||||
getMaxHeap() {
|
||||
return this.#maxHeap;
|
||||
}
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
@ -145,3 +150,8 @@ console.log(`\n堆元素数量为 ${size}`);
|
||||
/* 判断堆是否为空 */
|
||||
let isEmpty = maxHeap.isEmpty();
|
||||
console.log(`\n堆是否为空 ${isEmpty}`);
|
||||
|
||||
|
||||
module.exports = {
|
||||
MaxHeap,
|
||||
};
|
||||
|
||||
34
codes/javascript/chapter_heap/top_k.js
Normal file
34
codes/javascript/chapter_heap/top_k.js
Normal file
@ -0,0 +1,34 @@
|
||||
/**
|
||||
* File: top_k.js
|
||||
* Created Time: 2023-08-13
|
||||
* Author: Justin (xiefahit@gmail.com)
|
||||
*/
|
||||
|
||||
const { MaxHeap } = require('./my_heap');
|
||||
|
||||
/* 基于堆查找数组中最大的 k 个元素 */
|
||||
function top_k_heap(nums, k) {
|
||||
// 使用大顶堆 MaxHeap,对数组 nums 取相反数
|
||||
const invertedNums = nums.map(num => -num);
|
||||
// 将数组的前 k 个元素入堆
|
||||
const heap = new MaxHeap(invertedNums.slice(0, k));
|
||||
// 从第 k+1 个元素开始,保持堆的长度为 k
|
||||
for (let i = k; i < invertedNums.length; i++) {
|
||||
// 若当前元素小于堆顶元素,则将堆顶元素出堆、当前元素入堆
|
||||
if (invertedNums[i] < heap.peek()) {
|
||||
heap.pop();
|
||||
heap.push(invertedNums[i]);
|
||||
}
|
||||
}
|
||||
// 取出堆中元素
|
||||
const maxHeap = heap.getMaxHeap();
|
||||
// 对堆中元素取相反数
|
||||
const invertedMaxHeap = maxHeap.map(num => -num);
|
||||
return invertedMaxHeap;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
const nums = [1, 7, 6, 3, 2];
|
||||
const k = 3;
|
||||
const res = top_k_heap(nums, k);
|
||||
console.log(`最大的 ${k} 个元素为`, res);
|
||||
Reference in New Issue
Block a user