2022-1-29 Leetcode 692.前K个高频单词

在这里插入图片描述
在这里插入图片描述
这道题中学到的几个知识点:

优先队列的排序规则是什么?
The comparison function used to determine whether one element is smaller than another element.If Compare(x,y) is true, then x is smaller than y.The element returned by Q.top() is the largest element in the priority queue.That is, it has the property that, for every other element x in the priority queue, Compare(Q.top(), x) is false.

pair 的比较规则是什么?
先比较第一个的大小,如果第一个相等,再比较第二个的大小。
具体的函数实现如下:
template<class _Ty1,
class _Ty2> inline
bool operator<(const pair<_Ty1, _Ty2>& _Left,
const pair<_Ty1, _Ty2>& _Right)
{ // test if _Left < _Right for pairs
return (_Left.first < _Right.first ||
!(_Right.first < _Left.first) && _Left.second < _Right.second);
}

依然不明白的问题,为什么 最终得到的结果需要反转?
因为优先队列排序后,顶端是出现频率最小的字母,也是第一个出队列的。所以放入 vector 的时候,也是出现频率最小的字母在 vector 前面。所以需要反转。
为什么不可以直接安排字典序小的在底端?
反转之后字典序大的字母就在前端了,就无法得到正确的答案了。

class Solution {
public:
    struct cmp{
        bool operator()(const pair<string,int>& a,const pair<string,int>& b){
            if(a.second != b.second)
            return a.second > b.second;
            //小的排在顶端
           // else return a.first < b.first;
           return a < b;
           //如果第二个相等,字典序最大的在顶端
           //
        // if(a.second == b.second)
        // return a < b;
        // return a.second > b.second;
        }
    };
    vector<string> topKFrequent(vector<string>& words, int k) {
        unordered_map<string,int> myMap;
        for(auto& s:words){
            myMap[s]++;
        }
        priority_queue<pair<string,int>,vector<pair<string,int>>,cmp> que;
        for(auto &p:myMap){
            que.push(p);
            if(que.size() > k){
                que.pop();
            }
        }
        vector<string> ret;
        while(!que.empty()){
            ret.push_back(que.top().first);
            que.pop();
        }
       reverse(ret.begin(),ret.end());
       //没有看明白为什么需要反转。
       
        return ret;
        
    }
};

参考文章:STL | priority_queue(优先队列)基本用法

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值