解题思路:使用堆排序
class Solution { public: void HeapAdjust(vector<int> &nums,int i,int heapsize) { int left = 2*i+1; int right = 2*i+2; int smaller = i; if(left < heapsize && nums[smaller] >= nums[left]) smaller = left; if(right < heapsize && nums[smaller] >= nums[right]) smaller = right; if(smaller != i) { int temp = nums[smaller]; nums[smaller] = nums[i]; nums[i] = temp; HeapAdjust(nums, smaller, heapsize); } } vector<int> GetLeastNumbers_Solution(vector<int> input, int k) { int n = input.size(); for(int i = n/2;i>=0;--i) HeapAdjust(input, i, n); vector<int> res; for(int i = n-1;i>=n-k;--i) { res.push_back(input[0]); swap(input[0],input[i]); HeapAdjust(input, 0, i); } return res; } };