海量数据TopK问题

海量数据TopK问题

1.需求

从海量数据中找出出现次数最少的前K个值,且算法复杂度为O(n)。

2.分析

可以使用大根堆来实现。迭代数据,在迭代过程中,堆里面维护了目前为止的遇到的前K个重复次数最小的元素。迭代完成时,取出即可。

Tips:求最小/最少用大根堆,求最多/最大用小根堆。

3.代码实现

#include <iostream>
#include <queue>
#include <ctime>
#include <random>
#include <vector>
#include <unordered_map>
#include <functional>


using namespace std;

// 利用大根堆求数据重复次数最小的的前K个值问题
// 镜像问题同解

int main() {

	vector<int> nums;
	srand(time(nullptr));
	for (int i = 0; i < 10000; ++i) {
		nums.push_back(rand() % 1000);
	}

	unordered_map<int, int> cntHash;
	for (int i : nums) {
		cntHash[i]++;
	}

	using Type = pair<int, int>;
	using Cmp = function<bool(const Type&, const Type&)>;

	// 自定义比较器,创建大根堆
	priority_queue<Type, vector<Type>, Cmp> maxHeap(
		[](const Type& lhs, const Type& rhs) {
			return lhs.second < rhs.second;
		}
	);

	int K = 3;
	auto it = cntHash.begin();
	for (int i = 0; i < K; ++i, ++it) {
		maxHeap.push(*it);
	}

	while (it != cntHash.end()) {
		if (it->second < maxHeap.top().second) {
			maxHeap.pop();
			maxHeap.push(*it);
		}
		++it;
	}

	while (!maxHeap.empty()) {
		cout << "key:" << maxHeap.top().first <<
			" cnt:" << maxHeap.top().second << endl;
		maxHeap.pop();
	}

	return 0;
}

4.算法复杂度

大根堆的调整为O(logk)的时间复杂度,k为大根堆的层数。因此是常量时间,可以去掉。只剩下O(n)的遍历元素的时间。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值