0
点赞
收藏
分享

微信扫一扫

NC97 字符串出现次数的TopK问题

NC97 字符串出现次数的TopK问题_i++
NC97 字符串出现次数的TopK问题_散列表_02
网友答案

class Solution {
public:
/**
* return topK string
* @param strings string字符串vector strings
* @param k int整型 the k
* @return string字符串vector<vector<>>
*/
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);
}
};
vector<vector<string> > topKstrings(vector<string>& strings, int k) {
// write code here
vector<vector<string> > res;
if(strings.size() == 0)
return res;

unordered_map<string, int> hash;
for(auto c : strings)
hash[c] ++;

priority_queue<pair<string, int>, vector<pair<string, int>>, cmp> q;
int i = 0;
for(auto c : hash)
{
if(i < k) q.push(c);
else
{
if(c.second > q.top().second || (c.second == q.top().second && c.first < q.top().first))
{
q.pop();
q.push(c);
}
}
i++;
}
while(!q.empty())
{
res.push_back({q.top().first, to_string(q.top().second)});
q.pop();
}

reverse(res.begin(), res.end());
return res;
}
};


举报

相关推荐

0 条评论