欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Leetcode 692. Top K Frequent Words

程序员文章站 2022-04-25 19:09:52
...

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Leetcode 692. Top K Frequent Words

2. Solution

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/
相关标签: Leetcode