Algorithm|Leetcode 692. Top K Frequent Words

【Algorithm|Leetcode 692. Top K Frequent Words】文章作者:Tyan
博客:noahsnail.com|CSDN|简书
1. Description Algorithm|Leetcode 692. Top K Frequent Words
文章图片

2. Solution

bool compare(pair& a, pair& b) { if(a.second == b.second) { return a.first < b.first; } return a.second > b.second; }class Solution { public: vector topKFrequent(vector& words, int k) { vector result; unordered_map stat; for(string word: words) { stat[word]++; } vectorstring, 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/

    推荐阅读