首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

Leetcode 692. Top K Frequent Words

版权声明:博客文章都是作者辛苦整理的,转载请注明出处,谢谢! https://cloud.tencent.com/developer/article/1433862

文章作者:Tyan

博客:noahsnail.com | CSDN | 简书

1. Description

2. Solution

代码语言:javascript
复制
bool compare(pair<string, int>& a, pair<string, int>& b) {
    if(a.second == b.second) {
        return a.first < b.first;
    }
    return a.second > b.second;
}

class Solution {
public:
    vector<string> topKFrequent(vector<string>& words, int k) {
        vector<string> result;
        unordered_map<string, int> stat;
        for(string word: words) {
            stat[word]++;
        }
        vector<pair<string, int>> values;
        for(auto val: stat) {
            values.push_back(val);
        }
        sort(values.begin(), values.end(), compare);
        for(int i = 0; i < k; i++) {
            result.push_back(values[i].first);
        }
        return result;
    }
};

Reference

  1. https://leetcode.com/problems/top-k-frequent-words/description/
下一篇
举报
领券