前k大个数

#include <cstdlib>
#include <cstdio>
#include <vector>
#include <map>
#include <algorithm>
using namespace std;

void qfind(vector<int>& a, int k, int left, int right, vector<int>&res ) {
	if (left > right || k <= 0) return;
	if (right - left + 1 <= k) {
		while (left <= right) res.push_back(a[left++]);
		return;
	}

	int pivot = a[left];
	int i = left, j = right;
	while (i < j) {
		while (i < j && a[j] > pivot) j--;
		if (i < j) a[i++] = a[j];
		while (i < j && a[i] <= pivot) i++;
		if (i < j) a[j--] = a[i];
	}
	a[i] = pivot;
	qfind(a, k, left, i - 1 , res);
	if (k - (i-1-left + 1) > 0) res.push_back(a[i]);
	qfind(a, k-(i-left+1), i + 1, right, res);
}
vector<int> findKth(vector<int>& a, int k) {
	std::vector<int> res;
	qfind(a, k, 0, a.size() - 1, res);
	return res;
}
vector<int> findKth_heap(vector<int>& a, int k) {
	if (a.size() <= k) return a;
	vector<int> h(a.begin(), a.begin()+k);
	//auto cmp = (const int x, const int y){return x < y;};
	// max heap
	make_heap(h.begin(), h.end());
	for (int i = k; i < a.size(); i++) {
		if (a[i] < h[0]) {
			pop_heap(h.begin(), h.end());
			h[k-1] = a[i];
			push_heap(h.begin(), h.end());
		}
	}
	return h;
}

void p(const vector<int>& a) {
	for (auto i = a.begin(); i != a.end(); i++) printf("%d ", *i);
	printf("\n");
}
int main() {
	int a[] = {-1,1,1,1,1,1,1,1,11};
	//int a[] = {9,8,7,6,45,5,4,3,4,2,1,1};
	//int a[] = {1, 2,3,4 ,5 ,6, 7 ,8};
	vector<int> v(a, a + sizeof(a) / sizeof(int));
	auto res = findKth(v, 5);
	auto res2 = findKth_heap(v, 5);
	sort(res.begin(), res.end());
	sort(res2.begin(), res2.end());
	p(res);
	p(res2);
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值