classSolution { public: intfindKthLargest(vector<int>& nums, int k){ srand((unsigned)time(NULL)); int n = nums.size(); returngetKth(nums, k - 1, 0, n - 1); }
intgetKth(vector<int>& nums, int k, int left, int right){ if(right != left){ int random = rand() % (right - left) + left; swap(nums[random], nums[right]); } int idx = partition(nums, left, right); if(idx == k){ return nums[idx]; }elseif(idx > k){ returngetKth(nums, k, left, idx - 1); }elseif(idx < k){ returngetKth(nums, k, idx + 1, right); } return-1; }
intpartition(vector<int>& nums, int left, int right){ int begin = left - 1; int key = nums[right]; for(int i = left; i < right; ++i){ if(nums[i] > key){ swap(nums[++begin], nums[i]); } } swap(nums[++begin], nums[right]); return begin; } };