zoukankan      html  css  js  c++  java
  • 692. Top K Frequent Words

    问题描述:

    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.

    解题思路:

    1.遍历数组用hashmap存储string和其出现的频率

    2.在c++中hashmap是用pair存储的key 和 value的键值对,我们可以用struct cmp重写比较器

    3.创建最大堆,将pair压入堆中

    4.从堆中取出前k个值

    需要注意的是:

      重写比较器时要考虑频率相等的情况,这里要求按字母顺序输出。

    代码:

    class Solution {
    public:
        vector<string> topKFrequent(vector<string>& words, int k) {
            unordered_map<string, int> m;
            priority_queue<pair<string,int>, vector<pair<string, int>>, cmp > h;
            for(string w : words){
                m[w]++;
            }
            
            for(auto p : m){
                h.push(p);
                
            }
            vector<string> ret;
            for(int i = 0; i < k; i++){
                ret.push_back(h.top().first);
                h.pop();
            }
            return ret;
        }
    private:
        struct cmp{
            bool operator() (const pair<string, int> &p1, const pair<string,int> &p2){
                return p1.second < p2.second || (p1.second==p2.second && p1.first> p2.first);
            }
        };
    };
  • 相关阅读:
    树莓派4B
    SpringBoot 自定义 info Actuator 原理
    RestTemplate翻译serviceId过程
    ISA, ABI, API区别
    01.编译器结构
    【Git123】Git SSH Key支持多账号
    【消息中间件123】Solace PubSub+ Event Broker介绍
    【ETL123】
    【Http123】Http Timeout
    【性能123】Linux性能之“平均负载”
  • 原文地址:https://www.cnblogs.com/yaoyudadudu/p/9175898.html
Copyright © 2011-2022 走看看