classSolution { public: vector<int> topKMin(vector<int>& nums, int k){ if (k < 1 || k > nums.size()) { return {}; } int start = 0, end = nums.size() - 1; int index = partition(nums, start, end); while (index != k - 1) { if (index > k - 1) { end = index - 1; index = partition(nums, start, end); } else { start = index + 1; index = partition(nums, start, end); } }
return vector<int>(begin(nums), begin(nums) + k); } private: intpartition(vector<int>& nums, int l, int r){ if(nums.empty() || l < 0 || r >= nums.size()) return-1; int pivotIndex = randomNum(l, r); swap(nums[pivotIndex], nums[r]);
int smaller = l - 1; for (int i = l; i < r; ++i) { if (nums[i] <= nums[r]) { ++smaller; swap(nums[smaller], nums[i]); } } ++smaller; swap(nums[smaller], nums[r]); return smaller; }
intrandomNum(int x, int y){ srand(time(0)); // use system time as seed return x + rand() % (y - x + 1); } };