TopK问题(百度面试)

题目描述(Easy)

找到最大的十个数 and 如果文件很大,不能一次读入

算法分析

1. 快排的partition函数,以第k个数作为key时,大于k的右边的数即为所求;

2. 构建小顶堆;

Partition实现:

class Solution {
public:
    vector<int> GetLeastNumbers_Solution(vector<int> input, int k) {
        if (input.empty() || k <= 0 || k > input.size()) return vector<int>();
        
        int loc = partition(input, 0, input.size()-1);
        while (loc != k) {
            if (loc < k) {
                loc = partition(input, loc + 1, input.size()-1);
            } else if (loc > k) {
                loc = partition(input, 0, loc - 1);
            }
        }
        
        return vector<int>(input.begin(), input.begin()+k);
    }
    
    
    int partition(vector<int> &arr, int start, int end)
    {
        int key = arr[start];
        
        while(start < end) {
            while (start < end && arr[end] >= key) --end;
            arr[start] = arr[end];
            while (start < end && arr[start] <= key) ++start;
            arr[end] = arr[start];
        }
        
        arr[start] = key;
        return start;
    }
};

最小堆实现:

#include<iostream>
#include<vector>
#include <algorithm>
#include <functional>

using namespace std;

int main()

{
	// 最小堆
	int n, num;
	cin >> n;
	vector<int> max_heap(n, 0);
	for (int i = 0; i < n; ++i) cin >> max_heap[i];
	make_heap(max_heap.begin(), max_heap.end(), greater<int>());

	while (cin >> num) {
		max_heap.push_back(num);
		push_heap(max_heap.begin(), max_heap.end(), greater<int>());

		pop_heap(max_heap.begin(), max_heap.end(), greater<int>());
		max_heap.pop_back();
	}

	sort_heap(max_heap.begin(), max_heap.end(), greater<int>());
	for (int i = 0; i < n; ++i)
		cout << max_heap[i] << " ";
	cout << endl;
	return 0;

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值