LeetCode #692 - Top K Frequent Words

本文介绍了一种算法,用于从非空单词列表中找出出现频率最高的k个单词。算法首先使用哈希表统计每个单词的出现次数,然后通过优先队列(最小堆)保持k个最高频单词。最后,返回按频率降序且字母顺序排列的单词列表。

题目描述:

Given a non-empty list of words, return the k most frequent elements.

Your answer should be sorted by frequency from highest to lowest. If two words have the same frequency, then the word with the lower alphabetical order comes first.

Example 1:

Input: ["i", "love", "leetcode", "i", "love", "coding"], k = 2

Output: ["i", "love"]

Explanation: "i" and "love" are the two most frequent words. Note that "i" comes before "love" due to a lower alphabetical order.

Example 2:

Input: ["the", "day", "is", "sunny", "the", "the", "the", "sunny", "is", "is"], k = 4

Output: ["the", "is", "sunny", "day"]

Explanation: "the", "is", "sunny" and "day" are the four most frequent words, with the number of occurrence being 4, 3, 2 and 1 respectively.

Note:

1. You may assume k is always valid, 1 ≤ k ≤ number of unique elements.

2. Input words contain only lowercase letters.

Follow up:

1. Try to solve it in O(n log k) time and O(n) extra space.

class comp{
public:    
    bool operator()(pair<string,int> a, pair<string,int> b)
    {   //优先队列中将次数较小的元素置于队首,这样删除的时候也是先删除频率低的元素
        if(a.second>b.second) return true;
        else if(a.second==b.second&&a.first<b.first) return true;//字典序大的元素排前
        else return false;
    }
};

class Solution {
public:
    vector<string> topKFrequent(vector<string>& words, int k) {
        unordered_map<string,int> hash;
        for(string word:words)
        {
            if(hash.count(word)==0) hash[word]=1;
            else hash[word]++;
        }
        priority_queue<pair<string,int>,vector<pair<string,int>>,comp> q;
        for(auto x:hash)
        {
            if(q.size()<k) q.push({x.first,x.second});
            else
            {
                q.push({x.first,x.second});
                q.pop();
            }
        }
        vector<string> result;
        while(!q.empty())
        {
            result.push_back(q.top().first);
            q.pop();
        }
        //队首的元素次数较小,需要将result的元素翻转
        reverse(result.begin(),result.end());
        return result;
    }
};

 

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值