通过哈希表统计每个字符串出现的次数,pair<string,int>,自定义排序lambda对象,取前k个即可。
class Solution {
public:
/**
* return topK string
* @param strings string字符串vector strings
* @param k int整型 the k
* @return string字符串vector<vector<>>
*/
vector<vector<string> > topKstrings(vector<string>& strings, int k) {
unordered_map<string,int> un_map{};
for(auto str: strings) un_map[str]++;
auto cmp=[](pair<string,int> a,pair<string,int> b){
if(a.second==b.second) return a.first<b.first;
else return a.second > b.second;
};
vector<pair<string,int>> vec{};
for(auto& x: un_map) vec.push_back(x);
sort(vec.begin(),vec.end(),cmp);
vector<vector<string>> result;
for(int i=0;i<k;i++){
vector<string> res{};
res.push_back(vec[i].first);
res.push_back(to_string(vec[i].second));
result.push_back(res);
}
return result;
}
};