【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;
};
相关推荐
玛丽莲茼蒿9 小时前
Leetcode hot100 每日温度【中等】
算法·leetcode·职场和发展
样例过了就是过了9 小时前
LeetCode热题100 分割等和子集
数据结构·c++·算法·leetcode·动态规划
北顾笙98010 小时前
day38-数据结构力扣
数据结构·算法·leetcode
m0_6294947310 小时前
LeetCode 热题 100-----14.合并区间
数据结构·算法·leetcode
xin_nai10 小时前
LeetCode热题100(Java)(5)普通数组
算法·leetcode·职场和发展
水蓝烟雨12 小时前
3337. 字符串转换后的长度 II
算法·leetcode
_日拱一卒12 小时前
LeetCode:226翻转二叉树
数据结构·算法·leetcode
踩坑记录12 小时前
leetcode hot100 64. 最小路径和 medium 递归优化
leetcode·深度优先
样例过了就是过了13 小时前
LeetCode热题100 最长有效括号
c++·算法·leetcode·动态规划
水蓝烟雨13 小时前
3335. 字符串转换后的长度 I
算法·leetcode