Advertisement
STANAANDREY

Smallest K Integers O(n)

Jun 17th, 2020
1,591
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.06 KB | None | 0 0
  1. class Solution {
  2.     int partition(vector<int> &nums, int left, int right) {
  3.         int randomIndex = left + rand() % (right - left + 1);
  4.         std::swap(nums[randomIndex], nums[right]);
  5.         int value = nums[right];
  6.         int correctIndex = left;
  7.         for (int i = left; i <= right; i++) {
  8.             if (nums[i] <= value) {
  9.                 std::swap(nums[correctIndex++], nums[i]);
  10.             }
  11.         }
  12.         return correctIndex - 1;
  13.     }
  14.    
  15.     void smallestKNums(vector<int>& nums, int left, int right, int k) {
  16.         if (left >= right) {
  17.             return;
  18.         }
  19.         int pivot = partition(nums, left, right);
  20.         if (pivot - left + 1 >= k) {
  21.             smallestKNums(nums, left, pivot - 1, k);
  22.         } else {
  23.             smallestKNums(nums, pivot + 1, right, k - (pivot - left + 1));
  24.         }
  25.     }
  26.    
  27. public:
  28.     vector<int> kSmallest(vector<int>& nums, int k) {
  29.         const int n = nums.size();
  30.         smallestKNums(nums, 0, n - 1, k);
  31.         return vector<int>(nums.begin(), nums.begin() + k);
  32.     }
  33. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement