1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
| class Solution { private: int quickselect(vector<int> &nums, int l, int r, int index) { int pos = randomPartition(nums, l, r); if(pos == index) { return nums[pos]; } else if(pos < index) { return quickselect(nums, pos + 1, r, index); } else { return quickselect(nums, l, pos - 1, index); }
} int randomPartition(vector<int> &nums, int l, int r) { int q = rand() % (r - l + 1) + l; swap(nums[q], nums[r]); return partition(nums, l, r);
} int partition(vector<int> &nums, int l, int r){ int x = nums[r]; int i = l - 1; for(int n = l;n < r;n++) { if(nums[n] < x) { i++; swap(nums[i], nums[n]); } } swap(nums[i + 1], nums[r]); return i + 1; } public: int findKthLargest(vector<int>& nums, int k) { srand((unsigned)time(NULL)); return quickselect(nums, 0, nums.size() - 1, nums.size() - k ); } };
|