问题描述
给一非空的单词列表,返回前 k 个出现次数最多的单词。
返回的答案应该按单词出现频率由高到低排序。如果不同的单词有相同出现频率,按字母顺序排序。
示例 1:
输入: ["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 次。
输入说明
首先输入单词列表的单词数目n,
然后输入n个单词,以空格分隔
最后输入整数k。
假定 k 总为有效值, 1 ≤ k ≤ 集合元素数。
输入的单词均由小写字母组成。
输出说明
按题目要求输出,单词之间以一个空格分隔,行首和行尾无多余空格。
输入范例
6
i love leetcode i love coding
2
输出范例
i love
实现思路
利用哈希表记录每一个字符串出现的频率,然后将哈希表中所有字符串进行排序,排序时,如果两个字符串出现频率相同,那么我们让两字符串中字典序较小的排在前面,否则我们让出现频率较高的排在前面。最后我们只需要保留序列中的前 k 个字符串即可。
实现代码
#include <iostream>
#include <vector>
#include <math.h>
#include<string>
#include<unordered_map>
#include<algorithm>
using namespace std;
bool cmp(const pair<string,int>&a,const pair<string,int>&b){
if(a.second==b.second) return a.first<b.first;
else return a.second>b.second;
}
class Solution {
public:
vector<string> topKFrequent(vector<string>& words, int k) {
unordered_map<string,int>mp;
vector<string>res;
for(int i = 0;i<words.size();i++){
mp[words[i]]++;//求单词出现频率
}
vector<pair<string,int>>tem;
for(auto it:mp){
tem.push_back(it);
}
sort(tem.begin(),tem.end(),cmp);//排序
for(int i = 0;i<k;i++){//取前k个
res.push_back(tem[i].first);
}
return res;
}
};
int main()
{
int n;
string t;
vector<string>nums;
cin>>n;
for(int i = 0;i<n;i++){
cin>>t;
nums.push_back(t);
}
int k;
cin>>k;
vector<string> res = Solution().topKFrequent(nums,k);
for(int i = 0;i<res.size();i++){
if(i!=res.size()-1) cout<<res[i]<<" ";
else cout<<res[i];
}
return 0;
}