专题十四_优先级队列

目录

1046. 最后一块石头的重量

解析

题解

703. 数据流中的第 K 大元素

解析

题解

692. 前K个高频单词

解析

题解


1046. 最后一块石头的重量

1046. 最后一块石头的重量

解析

题解

class Solution {
public:
    int lastStoneWeight(vector<int>& stones) {
        // 专题十四_优先级队列_最后一块石头重量_C++
        // 1.创建一个大根堆
        priority_queue<int> heap;
        // 2.将所有的元素丢进这个堆里面
        for(auto x : stones)
            heap.push(x);
        // 3.模拟这个过程
        while(heap.size() > 1)
        {
            int a = heap.top(); heap.pop();
            int b = heap.top(); heap.pop();
            if(a > b) heap.push(a - b);
        }
        return heap.size() ? heap.top() : 0;
    }
};

703. 数据流中的第 K 大元素

703. 数据流中的第 K 大元素

 

 

解析

 

题解

class KthLargest {
public:
    // 创建一个大小为 k 的小根堆
    priority_queue<int, vector<int>, greater<int>> heap;
    int _k; 
    KthLargest(int k, vector<int>& nums) {
        _k = k;
        for(auto x : nums)
        {
            heap.push(x);
            if(heap.size() > _k) heap.pop();
        }
    }
    
    int add(int val) {
        heap.push(val);
        if(heap.size() > _k) heap.pop();
        return heap.top();
    }
};

/**
 * Your KthLargest object will be instantiated and called as such:
 * KthLargest* obj = new KthLargest(k, nums);
 * int param_1 = obj->add(val);
 */

692. 前K个高频单词

692. 前K个高频单词

解析

题解

class Solution {
public:
    typedef pair<string, int> PSI;
    struct cmp{
        bool operator()(const PSI& a, const PSI& b)
        {
            if(a.second == b.second) // 频次相同,字典序按照大根堆的方式排序
            {
                return a.first < b.first;
            }
            return a.second > b.second; // 不同按频次大小排序,按照小根堆方式
        }
    };
    vector<string> topKFrequent(vector<string>& words, int k) {
        // 80.专题十四_优 先级队列_前 K 个高频单_C++
        // 1.统计一下每个单词的频次
        unordered_map<string, int> hash;
        for(auto& s : words) hash[s]++;

        // 2.创建一个大小为 k 的堆
        priority_queue<PSI, vector<PSI>, cmp> heap;

        // 3.TpoK 的主逻辑
        for(auto& psi : hash)
        {
            heap.push(psi);
            if(heap.size() > k) heap.pop();
        }

        // 4.提取结果
        vector<string> ret(k);
        for(int i = k - 1; i >= 0; i--)
        {
            ret[i] = heap.top().first;
            heap.pop();
        }
        return ret;
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

清风玉骨

爱了!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值