LeetCode 692: Top K Frequent Words (最小堆好题)

这篇博客讨论了如何解决LeetCode上的692题,即找出数组中出现频率最高的k个单词。解决方案包括使用unordered_map统计单词频率,然后使用自定义比较函数的优先队列(最小堆)进行排序。博客中展示了不同实现方式,包括使用lambda表达式简化代码,以及使用结构体Node直接比较。
摘要由CSDN通过智能技术生成

LeetCode 692. Top K Frequent Words
Medium

5302

278

Add to List

Share
Given an array of strings words and an integer k, return the k most frequent strings.

Return the answer sorted by the frequency from highest to lowest. Sort the words with the same frequency by their lexicographical order.

Example 1:

Input: words = [“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: words = [“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.

Constraints:

1 <= words.length <= 500
1 <= words[i].length <= 10
words[i] consists of lowercase English letters.
k is in the range [1, The number of unique words[i]]

Follow-up: Could you solve it in O(n log(k)) time and O(n) extra space?

Accepted
437,840
Submissions
792,815

解法1:用unordered_map和最小堆。注意最小堆的元素是pair<string, int>,跟unordered_map的元素类型一样。

unordered_map<string, int> freqs;
struct cmp {
    bool operator() (const pair<string, int> &a, const pair<string, int> &b) const {
        return (a.second > b.second) || (a.second == b.second && a.first < b.first);
    }
};

class Solution {
public:
    vector<string> topKFrequent(vector<string>& words, int k) {
        freqs.clear();
        int len = words.size();
        for (auto word : words) {
            freqs[word]++;
        }
        priority_queue<pair<string, int>, vector<pair<string, int>>, cmp> minHeap;
    
        for (auto f : freqs) {
            minHeap.push(f);
            if (minHeap.size() > k) minHeap.pop();
        }
        vector<string> res;
        while (!minHeap.empty()) {
            res.push_back(minHeap.top().first);
            minHeap.pop();
        }
        reverse(res.begin(), res.end());
        return res;
    }
   
};

采用lambda表达式,上面代码可以简化一点:

class Solution {
public:
    vector<string> topKFrequent(vector<string>& words, int k) {
        unordered_map<string, int> freqs;
        freqs.clear();
        int len = words.size();
        for (auto word : words) {
            freqs[word]++;
        }
        auto cmp = [&](const pair<string, int> &a, const pair<string, int> &b) {
            return (a.second > b.second) || (a.second == b.second && a.first < b.first);
        };
        priority_queue<pair<string, int>, vector<pair<string, int>>, decltype(cmp)> minHeap(cmp);
    
        for (auto f : freqs) {
            minHeap.push(f);
            if (minHeap.size() > k) minHeap.pop();
        }
        vector<string> res;
        while (!minHeap.empty()) {
            res.push_back(minHeap.top().first);
            minHeap.pop();
        }
        reverse(res.begin(), res.end());
        return res;
    }
};

3刷:用decltype定义cmp。

class Solution {
public:
    vector<string> topKFrequent(vector<string>& words, int k) {
        unordered_map<string, int> freqs;
        int len = words.size();
        for (auto word : words) {
            freqs[word]++;
        }
        auto cmp = [&](string s1, string s2){
            if (freqs[s1] > freqs[s2]) return true;
            if (freqs[s1] == freqs[s2]) return s1 < s2;
            return false;        
        };
        priority_queue<string, vector<string>, decltype(cmp)> minHeap(cmp);
    
        for (auto s : freqs) {
            minHeap.push(s.first);
            if (minHeap.size() > k) minHeap.pop();
        }
        vector<string> res;
        while (!minHeap.empty()) {
            res.push_back(minHeap.top());
            minHeap.pop();
        }
        reverse(res.begin(), res.end());
        return res;
    }
   
};

4刷:

struct Node {
    string str;
    int freq;
    Node(string s, int f) : str(s), freq(f) {}
    bool operator < (const Node & node) const {
        if (freq > node.freq) return true;
        if (freq < node.freq) return false;
        return str < node.str;
    }
};

class Solution {
public:
    vector<string> topKFrequent(vector<string>& words, int k) {
        int n = words.size();
        priority_queue<Node> minHeap;
        unordered_map<string, int> str2Freq;
        for (auto word : words) str2Freq[word]++;
        int index = 0;
        for (auto elem : str2Freq) {
            index++;
            minHeap.push(Node(elem.first, elem.second));
            if (index > k) minHeap.pop();
        }
        vector<string> res;
        while (!minHeap.empty()) {
            auto top = minHeap.top();
            minHeap.pop();
            res.push_back(top.str);
        }
        reverse(res.begin(), res.end());
        return res;
    }
   
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值