题解 | 字符串出现次数的TopK问题

字符串出现次数的TopK问题

https://www.nowcoder.com/practice/fd711bdfa0e840b381d7e1b82183b3ee

#include <queue>
#include <string>
#include <unordered_map>
#include <vector>
#include <algorithm>

class Solution {
public:
    /**
      使用哈希表记录次数,然后转成vector,自定义排序,添加前k个
     */
    vector<vector<string> > topKstrings(vector<string>& strings, int k) {
        if(k==0){
            return {};
        }

        unordered_map<string, int> mp;

        for(const string& s:strings){
            mp[s]++;
        }

        vector< pair<string, int> > vec(mp.begin(), mp.end());

        sort( vec.begin(), vec.end(), [&](const pair<string, int>& a, 
            const pair<string, int>& b){
                if(a.second == b.second){
                    return a.first < b.first;  //二次排序
                }
                return a.second>b.second;} );  //return 排序规则; 

        vector< vector<string> > ans;
        for(int i=0; i<k; i++){
            ans.push_back( {vec[i].first, to_string(vec[i].second)} );
        }

        return ans;
    }
};

全部评论

相关推荐

不愿透露姓名的神秘牛友
07-23 14:18
点赞 评论 收藏
分享
能干的三文鱼刷了10...:公司可能有弄嵌入式需要会画pcb的需求,而且pcb能快速直观看出一个人某方面的实力。看看是否有面试资格。问你问题也能ai出来,pcb这东西能作假概率不高
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务