LeetCode "Top K Frequent Elements"
2016-05-03 09:19
597 查看
A typical solution is heap based - "top K". Complexity is O(nlgk).
There is a O(n) one indeed - bucketing the frequencies.
https://leetcode.com/discuss/100636/c-o-nlogk-and-o-n-solutions
typedef pair<int, unsigned> Rec; struct Comp { bool operator()(const Rec &r1, const Rec &r2) { return r1.second > r2.second; } }; class Solution { public: vector<int> topKFrequent(vector<int>& nums, int k) { unordered_map<int, unsigned> hm; for(auto&v : nums) hm[v]++; priority_queue<Rec, vector<Rec>, Comp> q; for(auto &kv : hm) { Rec r(kv.first, kv.second); q.push(r); if(q.size() > k) q.pop(); } vector<int> ret; while(!q.empty()) { ret.push_back(q.top().first); q.pop(); } return ret; } };
There is a O(n) one indeed - bucketing the frequencies.
https://leetcode.com/discuss/100636/c-o-nlogk-and-o-n-solutions
相关文章推荐
- 【Arduino官方教程第一辑】示例程序 2-8 曲调2
- 【Arduino官方教程第一辑】示例程序 2-7 使用tone()函数弹奏一段小曲
- google base 之MessagePumpForUI
- bzoj 1345: [Baltic2007]序列问题Sequence(单调栈)
- Elasticsearch源码分析之一——使用Guice进行依赖注入与模块化系统
- LeetCode 270: Closest Binary Search Tree Value
- google base之IncomingTaskQueue
- 知问前端——日历UI(二)
- 纠结的名字 - 自动生成apk文件名
- The version of Gradle requested by the project.
- UICollectionView基本使用
- [BZOJ1345][Baltic2007]序列问题Sequence(单调栈)
- 读取日志文件,搜索关键字,打印关键字前5行。yield、deque实例
- 建造者(Builder)模式
- 知问前端——日历UI(一)
- Android 中文翻译:Build System Overview
- 新书到手 TRANSACTION PROCESSING:CONCEPTS AND TECHNIQUES
- leetcode_096 Unique Binary Search Trees
- 【Java学习-J.160430.0.16】笔记9-UUID生成
- Android_UI:Fragment