堆排序
class Solution {
public:
vector<int> getLeastNumbers(vector<int>& arr, int k) {
maxheap(arr, 0, k-1);
for(int i=k/2-1; i>=0; i--){
maxheap(arr, i, k-1);
}
for(int i=k; i<arr.size(); ++i){
if(arr[i]>arr[0]) continue;
else{
int temp = arr[i];
arr[i] = arr[0];
arr[0] = temp;
maxheap(arr, 0, k-1);
}
}
vector<int> res(arr.begin(), arr.begin()+k);
return res;
}
void maxheap(vector<int>& arr, int start, int end){
int dad = start;
int son = dad * 2 + 1;
while(son <= end){
if(son + 1 <= end && arr[son] < arr[son + 1]){
son ++;
}
if(arr[dad] >= arr[son]){
return;
}
else{
int temp = arr[dad];
arr[dad] = arr[son];
arr[son] = temp;
dad = son;
son = dad * 2 + 1;
}
}
}
};