鱼C论坛

 找回密码
 立即注册
查看: 2208|回复: 0

[技术交流] C++刷LeetCode(692. 前K个高频单词)【sort*】

[复制链接]
发表于 2020-6-30 11:49:59 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
题目描述:
  1. 给一非空的单词列表,返回前 k 个出现次数最多的单词。

  2. 返回的答案应该按单词出现频率由高到低排序。如果不同的单词有相同出现频率,按字母顺序排序。

  3. 示例 1:

  4. 输入: ["i", "love", "leetcode", "i", "love", "coding"], k = 2
  5. 输出: ["i", "love"]
  6. 解析: "i" 和 "love" 为出现次数最多的两个单词,均为2次。
  7.     注意,按字母顺序 "i" 在 "love" 之前。
  8.  

  9. 示例 2:

  10. 输入: ["the", "day", "is", "sunny", "the", "the", "the", "sunny", "is", "is"], k = 4
  11. 输出: ["the", "is", "sunny", "day"]
  12. 解析: "the", "is", "sunny" 和 "day" 是出现次数最多的四个单词,
  13.     出现次数依次为 4, 3, 2 和 1 次。
  14.  

  15. 注意:

  16. 假定 k 总为有效值, 1 ≤ k ≤ 集合元素数。
  17. 输入的单词均由小写字母组成。

  18. 来源:力扣(LeetCode)
  19. 链接:https://leetcode-cn.com/problems/top-k-frequent-words
  20. 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
复制代码


  1. class Solution {
  2. public:
  3.     static bool cmp(pair<string, int> &x, pair<string, int> &y){
  4.         if (x.second != y.second) return x.second > y.second;
  5.         return x.first < y.first;
  6.     }
  7.     vector<string> topKFrequent(vector<string>& words, int k) {
  8.         map <string,int> store;
  9.         for (auto word:words){
  10.             store[word]++;
  11.         }
  12.         vector<pair<string, int>> temp (store.begin(), store.end());
  13.         sort(temp.begin(), temp.end(), cmp);
  14.         vector<string> res;
  15.         for (int i = 0; i < k; i++){
  16.             res.push_back(temp[i].first);
  17.         }
  18.         return res;
  19.     }
  20. };
复制代码

本帖被以下淘专辑推荐:

小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-7-3 19:11

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表