priority_queue(六)692. 前K个高频单词 中等

692. 前K个高频单词

给定一个单词列表 words 和一个整数 k ,返回前 k 个出现次数最多的单词。

返回的答案应该按单词出现频率由高到低排序。如果不同的单词有相同出现频率, 按字典顺序 排序。

示例 1:

输入: words = ["i", "love", "leetcode", "i", "love", "coding"], k = 2
输出: ["i", "love"]
解析: "i" 和 "love" 为出现次数最多的两个单词,均为2次。
    注意,按字母顺序 "i" 在 "love" 之前。

示例 2:

输入: ["the", "day", "is", "sunny", "the", "the", "the", "sunny", "is", "is"], k = 4
输出: ["the", "is", "sunny", "day"]
解析: "the", "is", "sunny" 和 "day" 是出现次数最多的四个单词,
    出现次数依次为 4, 3, 2 和 1 次。

我们需要提取频次最高的前K个元素,那么就选择维护一个 K容量大小的小跟堆 小根堆就需要在仿函数里面对频次大的条件下返回True ,当频次相同的时候要选择字典序返回,这时候又需要满足一个大根堆的形式,让字典序考后的放在堆的最上面。

最终k容量的堆里面存放就是频次最高的前k个元素,堆顶元素为这k个元素中频次最小,不断从后往前pop出堆,然后放回res返回结果中。

struct Com {
    typedef pair<string, int> Node;
    bool operator()(const Node& left,const Node& right) 
    {
        仿函数  用于创建优先级队列
        if (left.second == right.second)
            return left.first < right.first;
        return (left.second > right.second)
    }
};
class Solution {
public:
    typedef pair<string, int> Node;
    vector<string> topKFrequent(vector<string>& words, int k) {
        map<string, int> dict;
        for (auto& e : words)
            dict[e]++;

        priority_queue<Node, vector<Node>, Com> heap;
        for (auto& e : dict)
        {
            heap.push(e);
            if (heap.size() > k)
                heap.pop();
        }
        // vector<string> res;
        // while (!heap.empty())
        // {
        //     res.push_back(heap.top().first);
        //     heap.pop();
        // }
        // reverse(res.begin(), res.end());

        vector<string> res(k);
        for(int i = k-1; i >= 0; i--)
        {
            res[i] = heap.top().first;
            heap.pop();
        }
        return res;
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值