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

字符串出现次数的TopK问题

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

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) {
        // write code here
        if (strings.size() == 0) {
            return {};
        }

        map<string, int> strCountMap;
        map<int, set<string>> countStrMap;

        for (string& str : strings) {
            strCountMap[str]++;
        }

        for (auto& [str, count] : strCountMap) {
            countStrMap[count].insert(str);
        }

        vector<vector<string>> result;
        int count = 0;
        for (auto it = countStrMap.rbegin(); it != countStrMap.rend(); it++) {
            if (countStrMap.count(it->first) != 0) {
                vector<string> vec;
                for (auto& str : it->second) {
                    if (count >= k) {
                        break;
                    }
                    vec.clear();
                    vec.push_back(str);
                    vec.push_back(to_string(it->first));
                    result.push_back(vec);
                    count++;
                }
            }
        }

        return result;
    }
};

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

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