【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;
};
相关推荐
玖剹19 小时前
队列+宽搜(bfs)
数据结构·c++·算法·leetcode·宽度优先
有一个好名字21 小时前
力扣-从字符串中移除星号
java·算法·leetcode
萧瑟其中~21 小时前
二分算法模版——基础二分查找,左边界查找与右边界查找(Leetcode的二分查找、在排序数组中查找元素的第一个位置和最后一个位置)
数据结构·算法·leetcode
AlenTech21 小时前
208. 实现 Trie (前缀树) - 力扣(LeetCode)
leetcode
iAkuya21 小时前
(leetcode)力扣100 36二叉树的中序遍历(迭代递归)
算法·leetcode·职场和发展
wangwangmoon_light21 小时前
1.1 LeetCode总结(线性表)_枚举技巧
算法·leetcode·哈希算法
有一个好名字1 天前
力扣-小行星碰撞
算法·leetcode·职场和发展
栈与堆1 天前
LeetCode-1-两数之和
java·数据结构·后端·python·算法·leetcode·rust
求梦8201 天前
【力扣hot100题】反转链表(18)
算法·leetcode·职场和发展