题解 | #最小的K个数#
最小的K个数
https://www.nowcoder.com/practice/6a296eb82cf844ca8539b57c23e6e9bf
#include <vector> class Solution { public: int partition(vector<int>& vec, int left, int right) { int pivot = vec[left]; int i = left + 1; for (int j = left + 1; j <= right; j++) { if (vec[j] < pivot) { swap(vec[i++], vec[j]); } } swap(vec[i - 1], vec[left]); return i - 1; } vector<int> GetLeastNumbers_Solution(vector<int>& input, int k) { vector<int> res; if (k == 0 || k > input.size()) return res; int left = 0, right = input.size() - 1; while (left <= right) { int index = partition(input, left, right); if (index == k - 1) { return vector<int>(input.begin(), input.begin() + k); } else if (index < k - 1) { left = index + 1; } else { right = index - 1; } } return res; } };