最小的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)\)。

关于复杂度,还可以用代入法证明:

\[T(n)=T(n/2)+n=T(n/4)+n/2+n=T(n/8)+n/4+n/2+n=...
\]

重复k次后:

\[T(n)=T(n/2^k)+n/2^{k-1}+...+n/2+n
\]

故:\(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的更多相关文章

  1. [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 ...

  2. C#版(打败99.28%的提交) - Leetcode 347. Top K Frequent Elements - 题解

    版权声明: 本文为博主Bravo Yeung(知乎UserName同名)的原创文章,欲转载请先私信获博主允许,转载时请附上网址 http://blog.csdn.net/lzuacm. C#版 - L ...

  3. [LeetCode] 347. Top K Frequent Elements 前K个高频元素

    Given a non-empty array of integers, return the k most frequent elements. Example 1: Input: nums = [ ...

  4. 【leetcode】347. Top K Frequent Elements

    题目地址:https://leetcode.com/problems/top-k-frequent-elements/ 从一个数组中求解出现次数最多的k个元素,本质是top k问题,用堆排序解决. 关 ...

  5. 【LeetCode】692. Top K Frequent Words 解题报告(Python)

    [LeetCode]692. Top K Frequent Words 解题报告(Python) 标签: LeetCode 题目地址:https://leetcode.com/problems/top ...

  6. 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 ...

  7. 大数据热点问题TOP K

    1单节点上的topK (1)批量数据 数据结构:HashMap, PriorityQueue 步骤:(1)数据预处理:遍历整个数据集,hash表记录词频 (2)构建最小堆:最小堆只存k个数据. 时间复 ...

  8. LeetCode "Top K Frequent Elements"

    A typical solution is heap based - "top K". Complexity is O(nlgk). typedef pair<int, un ...

  9. [IR] Ranking - top k

    PageRanking 通过: Input degree of link "Flow" model - 流量判断喜好度 传统的方式又是什么呢? Every term在某个doc中的 ...

  10. 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 ...

随机推荐

  1. 适用于 Mpvue 的微信小程序富文本解析自定义组件

    废话不多说,直接上方法: 首先 npm 安装 mpvue-wxparse npm i mpvue-wxparse 接下来:使用 <template> <div> <wxP ...

  2. 03使用Want Weapp进行路由跳转

    因为这里使用的是第三方库,所以你要引入哈. 在app.json中引入哈. "usingComponents": { "van-cell": "@van ...

  3. [编译] 7、在Linux下搭建安卓APP的开发烧写环境(makefile版-gradle版)—— 在Linux上用命令行+VIM开发安卓APP

    April 18, 2020 6:54 AM - BEAUTIFULZZZZ 目录 0 前言 1 gradle 安装配置 1.1 卸载系统默认装的gradle 1.2 下载对应版本的二进制文件 1.3 ...

  4. AJ学IOS 之ipad开发qq空间项目横竖屏幕适配

    AJ分享,必须精品 一:效果图 先看效果 二:结构图 如图所示: 其中用到了UIView+extension分类 Masonry第三方框架做子控制器的适配 NYHomeViewController对应 ...

  5. 聊聊Disruptor 和 Aeron 这两个开源库

    Disruptor The best way to understand what the Disruptor is, is to compare it to something well under ...

  6. .NET Core 发布时去掉多余的语言包文件夹

    用 .NET Core 3.x 作为目标框架时发布完之后,会发现多了很多语言包文件夹,类似于: 有时候,不想要生成这些语言包文件夹,需要稍微配置一下. 在 PropertyGroup 节点中添加如下的 ...

  7. 装机摸鱼日志--ubuntu16.04安装网易云音乐客户端

    之前装的网易云音乐不指定啥原因不能用了,所以打算重新装一个,但是进官网只有deepin15和ubuntu18.04版本的安装包.然后我装了一下18.04的安装包,但是没有成功.甚至因为更换glibc差 ...

  8. [linux][mysql] MySQL中information_schema是什么

    来源:MySQL中information_schema是什么 information_schema数据库是MySQL自带的,information_schema提供了访问数据库元数据的方式.这就是?元 ...

  9. redis:key命令(二)

    设置一个key:set name hello 获取一个key的值:get name 查看所有的key:keys * 查看key是否存在:exists name 移动key到指定库:move name ...

  10. css的变量教程,更强大的css

    当微软宣布 Edge 浏览器将支持 CSS 变量.这个重要的 CSS 新功能,所有主要浏览器已经都支持了.本文全面介绍如何使用它,你会发现原生 CSS 从此变得异常强大. 一.变量的声明 声明变量的时 ...