【LeetCode热题100(72/100)】前 K 个高频元素

题目地址: 链接

思路: 堆实现

ts 复制代码
class MaxHeap_{
    heap: [number, number][];
    size: number;
    constructor(map: Map<number, number>) {
        this.heap = [];
        this.size = 0;
        this.build(map);
    }

    private build(map: Map<number, number>): void {
        map.forEach((val, key) => {
            this.heap.push([key, val]);
        })
        this.size = this.heap.length;
        const parentNode = Math.floor((this.size - 1) / 2);
        for(let i = parentNode; i >= 0; i --) {
            this.sink(i);
        }
    }

    private sink(index: number): void {
        let [heap, size] = [this.heap, this.size];
        
        let maxIdx = index;
        let leftNode = 2 * index + 1;
        let rightNode= 2 * index + 2;

        if(leftNode < size && heap[maxIdx][1] < heap[leftNode][1]) {
            maxIdx = leftNode;
        }

        if(rightNode < size && heap[maxIdx][1] < heap[rightNode][1]) {
            maxIdx = rightNode;
        }

        if(index !== maxIdx) {
            [heap[maxIdx], heap[index]] = [heap[index], heap[maxIdx]];
            this.sink(maxIdx);
        }
    }

    public pop(): number {
        let heap = this.heap;
        let ans = this.getTop();
        heap[0] = heap[this.size - 1];
        this.size --;
        this.sink(0);
        return ans;
    }

    private getTop(): number {
        return this.heap[0][0];
    }
}
function topKFrequent(nums: number[], k: number): number[] {
    let map = new Map();
    for(const num of nums) {
        map.set(num, (map.get(num) ?? 0) + 1);
    }
    const maxheap = new MaxHeap_(map);

    let ans:number[] = [];
    for(let i = 0; i < k; i ++) {
        let idx = maxheap.pop();
        ans.push(idx);
    }
    
    return ans;
};
相关推荐
TracyCoder12319 小时前
LeetCode Hot100(27/100)——94. 二叉树的中序遍历
算法·leetcode
草履虫建模1 天前
力扣算法 1768. 交替合并字符串
java·开发语言·算法·leetcode·职场和发展·idea·基础
VT.馒头1 天前
【力扣】2721. 并行执行异步函数
前端·javascript·算法·leetcode·typescript
不穿格子的程序员1 天前
从零开始写算法——普通数组篇:缺失的第一个正数
算法·leetcode·哈希算法
VT.馒头2 天前
【力扣】2722. 根据 ID 合并两个数组
javascript·算法·leetcode·职场和发展·typescript
执着2592 天前
力扣hot100 - 108、将有序数组转换为二叉搜索树
算法·leetcode·职场和发展
52Hz1182 天前
力扣230.二叉搜索树中第k小的元素、199.二叉树的右视图、114.二叉树展开为链表
python·算法·leetcode
苦藤新鸡2 天前
56.组合总数
数据结构·算法·leetcode
菜鸟233号2 天前
力扣647 回文子串 java实现
java·数据结构·leetcode·动态规划
LiLiYuan.2 天前
【Cursor 中找不到LeetCode 插件解决办法】
算法·leetcode·职场和发展