题目描述(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;
}