博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
#Leetcode# 692. Top K Frequent Words
阅读量:5046 次
发布时间:2019-06-12

本文共 1685 字,大约阅读时间需要 5 分钟。

 

Given a non-empty list of words, return the k most frequent elements.

Your answer should be sorted by frequency from highest to lowest. If two words have the same frequency, then the word with the lower alphabetical order comes first.

Example 1:

Input: ["i", "love", "leetcode", "i", "love", "coding"], k = 2Output: ["i", "love"]Explanation: "i" and "love" are the two most frequent words.    Note that "i" comes before "love" due to a lower alphabetical order.

 

Example 2:

Input: ["the", "day", "is", "sunny", "the", "the", "the", "sunny", "is", "is"], k = 4Output: ["the", "is", "sunny", "day"]Explanation: "the", "is", "sunny" and "day" are the four most frequent words,    with the number of occurrence being 4, 3, 2 and 1 respectively.

 

Note:

  1. You may assume k is always valid, 1 ≤ k ≤ number of unique elements.
  2. Input words contain only lowercase letters.

 

Follow up:

  1. Try to solve it in O(n log k) time and O(n) extra space.

代码:

class Solution {public:    vector
topKFrequent(vector
& words, int k) { vector
res(k); unordered_map
freq; auto cmp = [](pair
& a, pair
& b) { return a.second > b.second || (a.second == b.second && a.first < b.first); }; priority_queue
, vector
>, decltype(cmp) > q(cmp); for (auto word : words) ++freq[word]; for (auto f : freq) { q.push(f); if (q.size() > k) q.pop(); } for (int i = res.size() - 1; i >= 0; --i) { res[i] = q.top().first; q.pop(); } return res; }};

  priority_queue 自定义排序 get    priority_queue 正常按照第一项从大到小 然后第二项从大到小就不符合题意需要第二项按从小到大 所以自定义

FH 睡着啦

转载于:https://www.cnblogs.com/zlrrrr/p/10340161.html

你可能感兴趣的文章
oracle插入数据
查看>>
【RL-TCPnet网络教程】第24章 RL-TCPnet之网络控制报文协议ICMP
查看>>
java学习笔记之String类
查看>>
Python Day12
查看>>
pymysql操作mysql
查看>>
Linux服务器删除乱码文件/文件夹的方法
查看>>
牛腩记账本core版本源码
查看>>
Word Break II
查看>>
UVA 11082 Matrix Decompressing 矩阵解压(最大流,经典)
查看>>
LOJ2362. 「NOIP2016」蚯蚓【单调队列】
查看>>
MVC导出Excle
查看>>
Knockout应用开发指南 第三章:绑定语法(1)
查看>>
jni 步骤
查看>>
SRP记录_20190418
查看>>
无线通讯
查看>>
Mongodb Manual阅读笔记:CH9 Sharding
查看>>
AX2009使用NPOI导出EXCEL2007
查看>>
如何删除NSDictionary或NSArray中的NSNull
查看>>
ueditor 结合easyui使用
查看>>
thymeleaf学习笔记
查看>>