首页 > 编程语言 >前K个高频单词 C++

前K个高频单词 C++

时间:2024-08-31 21:52:34浏览次数:6  
标签:love sunny C++ 单词 次数 vector words 高频

给定一个单词列表 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 次。
class Solution {
public:
    vector<string> topKFrequent(vector<string>& words, int k) 
    {
       map<string,int>countMap;
       for(auto e:words)
       {
            countMap[e]++;
       } 

       //1.将pair<string,int>键值对放到vector中,用sort排序,还要一个int比较仿函数,排完了,还需要对次数相同的按字母排
       //2.还是用multimap排
       multimap<int,string,greater<int>>sortMap;
       for(auto kv :countMap)
       {
            sortMap.insert(make_pair(kv.second,kv.first));
       }
        vector<string> v;
        for(auto e:sortMap)
        {
            v.push_back(e.second);
            if(--k==0)
                break;
            
            
        }    
        return v;
    }
};

标签:love,sunny,C++,单词,次数,vector,words,高频
From: https://blog.csdn.net/2403_85903590/article/details/141759229

相关文章