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

题目地址:链接

思路: 堆实现

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;
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值