TOP-K Problems
最小的K个数
- 直接数组排序,取出前K个。复杂度\(O(nlogn)\)。
- 分治
此题只要求出最小的K个数,并不要求这K个数有序。
我们可以借鉴快排中的partition做法,将比第K个数小的都放前面,其余都放后面,即得到答案,但是这种方法会改变原有数组:
class Solution {
public:
vector<int> topKMin(vector<int>& nums, int k) {
if (k < 1 || k > nums.size()) {
return {};
}
int start = 0, end = nums.size() - 1;
int index = partition(nums, start, end);
while (index != k - 1) {
if (index > k - 1) {
end = index - 1;
index = partition(nums, start, end);
}
else {
start = index + 1;
index = partition(nums, start, end);
}
}
return vector<int>(begin(nums), begin(nums) + k);
}
private:
int partition(vector<int>& nums, int l, int r) {
if(nums.empty() || l < 0 || r >= nums.size())
return -1;
int pivotIndex = randomNum(l, r);
swap(nums[pivotIndex], nums[r]);
int smaller = l - 1;
for (int i = l; i < r; ++i) {
if (nums[i] <= nums[r]) {
++smaller;
swap(nums[smaller], nums[i]);
}
}
++smaller;
swap(nums[smaller], nums[r]);
return smaller;
}
int randomNum(int x, int y) {
srand(time(0)); // use system time as seed
return x + rand() % (y - x + 1);
}
};
可以得到递归关系:\(T(n)=T(n/2)+n\),由主定理可知复杂度\(O(n)\)。
与快排不同的是:快排要处理2个子问题,故为\(T(n)=2T(n/2)+n\),复杂度\(O(nlogn)\)。
关于复杂度,还可以用代入法证明:
\]
重复k次后:
\]
故:\(T(n)=n+n/2+n/4+...+1=2n+1\)
- 堆/红黑树
主要思路是用容器存储K个数,之后不断更新:如果当前值小于容器最大值,替换最大值。
用最大堆作为容器,删除及插入\(O(lgk)\),故总复杂度\(O(nlgk)\):
// max heap
class Solution {
public:
priority_queue<int> topKMin(vector<int>& nums, int k) {
if (k < 1 || k > nums.size()) {
return {};
}
priority_queue<int> q;
for (vector<int>::iterator it = nums.begin(); it != nums.end(); ++it) {
if (q.size() < k) {
q.push(*it);
}
else {
if (q.top() > * it) {
q.pop();
q.push(*it);
}
}
}
return q;
}
};
当然也可以使用红黑树:
// multiset
class Solution {
public:
vector<int> topKMin(vector<int>& nums, int k) {
if (k < 1 || k > nums.size()) {
return {};
}
multiset<int, greater<int>> ms;
for (vector<int>::iterator it = nums.begin(); it != nums.end(); ++it) {
if (ms.size() < k) {
ms.insert(*it);
}
else {
if (*ms.begin() > * it) {
ms.erase(ms.begin());
ms.insert(*it);
}
}
}
return vector<int>(ms.begin(), ms.end());
}
};
之所以说这种解法适用于海量数据,是因为很多时候不能一次性把数据读入内存处理,这种解法可以从硬盘一次读一个,判断是否放入容器即可,只需要在内存中存储容器即可。
最常出现的K个数
- 统计出现频率,排序后取出前K个。复杂度\(O(nlgn)\)。
- 最小堆。维护K个数,如果新数的频率大于堆顶,替换之。复杂度\(O(nlgk)\)。
class Solution {
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
vector<int> ans;
unordered_map<int, int> cnt;
for (int i = 0; i < nums.size(); ++i) {
++cnt[nums[i]];
}
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> q;
for (auto p : cnt) {
q.emplace(p.second, p.first);
if (q.size() > k) {
q.pop();
}
}
for (int i = 0; i < k;++i) {
ans.push_back(q.top().second);
q.pop();
}
return ans;
}
};
- 桶排。用很多桶记录不同频率到对应数字的映射。时间\(O(n)\),空间\(O(n)\)。
class Solution {
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
vector<int> ans;
unordered_map<int, int> cnt;
int maxFre = 0;
for(const int i : nums) {
maxFre = max(maxFre, ++cnt[i]);
}
unordered_map<int, vector<int>> bucket; // freq -> nums
for(const auto& p : cnt) {
bucket[p.second].push_back(p.first);
}
for(int i = maxFre;i > 0;--i) {
for(int a : bucket[i]) {
ans.push_back(a);
if(ans.size() == k) {
return ans;
}
}
}
return ans;
}
};
TOP-K Problems的更多相关文章
- [LeetCode] Top K Frequent Elements 前K个高频元素
Given a non-empty array of integers, return the k most frequent elements. For example,Given [1,1,1,2 ...
- C#版(打败99.28%的提交) - Leetcode 347. Top K Frequent Elements - 题解
版权声明: 本文为博主Bravo Yeung(知乎UserName同名)的原创文章,欲转载请先私信获博主允许,转载时请附上网址 http://blog.csdn.net/lzuacm. C#版 - L ...
- [LeetCode] 347. Top K Frequent Elements 前K个高频元素
Given a non-empty array of integers, return the k most frequent elements. Example 1: Input: nums = [ ...
- 【leetcode】347. Top K Frequent Elements
题目地址:https://leetcode.com/problems/top-k-frequent-elements/ 从一个数组中求解出现次数最多的k个元素,本质是top k问题,用堆排序解决. 关 ...
- 【LeetCode】692. Top K Frequent Words 解题报告(Python)
[LeetCode]692. Top K Frequent Words 解题报告(Python) 标签: LeetCode 题目地址:https://leetcode.com/problems/top ...
- Leetcode 347. Top K Frequent Elements
Given a non-empty array of integers, return the k most frequent elements. For example,Given [1,1,1,2 ...
- 大数据热点问题TOP K
1单节点上的topK (1)批量数据 数据结构:HashMap, PriorityQueue 步骤:(1)数据预处理:遍历整个数据集,hash表记录词频 (2)构建最小堆:最小堆只存k个数据. 时间复 ...
- LeetCode "Top K Frequent Elements"
A typical solution is heap based - "top K". Complexity is O(nlgk). typedef pair<int, un ...
- [IR] Ranking - top k
PageRanking 通过: Input degree of link "Flow" model - 流量判断喜好度 传统的方式又是什么呢? Every term在某个doc中的 ...
- 347. Top K Frequent Elements
Given a non-empty array of integers, return the k most frequent elements. For example,Given [1,1,1,2 ...
随机推荐
- javascript 入门 之 bootstrap/bootstrap-table 安装方法
也和select2一样,可以有三种方法 1.远程调用CDN 2.用bower安装 3.下载 时间原因,暂时先讲第二种,其余两种,以后完善 1.进入根目录,执行bower install bootstr ...
- MySQL中information_schema 数据库 是干什么的
MySQL中information_schema是什么 大家在安装或使用MYSQL时,会发现除了自己安装的数据库以外,还有一个information_schema数据库. information_sc ...
- Cilium架构 (Cilium 2)
Cilium架构 译自:http://docs.cilium.io/en/stable/architecture/ 本文档描述了Cilium的架构.它通过记录BPF数据路径(datapath)的钩子来 ...
- Android 程序代码进行代码混淆
1.在Eclipse项目包下的project.properties文件中加入proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt ...
- 运输层--------运输层与网络层的关系、UDP、TCP
一.运输层与网络的区别: 网络层提供了主机之间的逻辑通信,而运输层为运行在不同主机上的进程之间提供了逻辑通信 二.实例证明: 考虑有两个家庭,一家位于美国东岸,一家位于美国西海岸,每家有12孩子.东海 ...
- 用Python绘制全球疫情变化地图
目前全球疫情仍然比较严重,为了能清晰地看到疫情爆发以来至现在全球疫情的变化趋势,我绘制了一张疫情变化地图,完整代码共 230 行,需要的朋友在公众号回复关键字 疫情地图 即可. 废话不多说,先上图 下 ...
- 【three.js 第一课】创建场景,显示几何体
<!DOCTYPE html> <html> <head> <title>demo1</title> </head> <s ...
- Some Modern Softwares' drawbacks: User experience 12/29/2015
In the nowadays, there are many APP in the PC or smart Phone. Some of them can't meet the customers' ...
- A - Chat Group Gym-101775A
题目连接:https://codeforces.com/gym/101775/problem/A 题解:就是累加组合数 但是直接由K累加到N肯定会TLE ,所以我们不妨判断不能组成group的情况,即 ...
- Flask接口开发过程中的心得2019.10.03
完善了一下慕课网实战中的post接口开发,得到了一些进步: 代码如下: #coding=utf-8 from flask import Flask from flask import request ...