【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;
};
相关推荐
TracyCoder1238 小时前
LeetCode Hot100(19/100)——206. 反转链表
算法·leetcode
踩坑记录9 小时前
leetcode hot100 94. 二叉树的中序遍历 easy 递归 dfs
leetcode
醉颜凉11 小时前
【LeetCode】打家劫舍III
c语言·算法·leetcode·树 深度优先搜索·动态规划 二叉树
达文汐11 小时前
【困难】力扣算法题解析LeetCode332:重新安排行程
java·数据结构·经验分享·算法·leetcode·力扣
一匹电信狗11 小时前
【LeetCode_21】合并两个有序链表
c语言·开发语言·数据结构·c++·算法·leetcode·stl
User_芊芊君子11 小时前
【LeetCode经典题解】搞定二叉树最近公共祖先:递归法+栈存路径法,附代码实现
算法·leetcode·职场和发展
培风图南以星河揽胜11 小时前
Java版LeetCode热题100之零钱兑换:动态规划经典问题深度解析
java·leetcode·动态规划
算法_小学生11 小时前
LeetCode 热题 100(分享最简单易懂的Python代码!)
python·算法·leetcode
执着25911 小时前
力扣hot100 - 234、回文链表
算法·leetcode·链表
熬夜造bug11 小时前
LeetCode Hot100 刷题路线(Python版)
算法·leetcode·职场和发展