classSolution { public: intfindKthLargest(vector<int>& nums, int k){ returnfind(nums, 0, nums.size() - 1, k); } // the goal is to intfind(vector<int>& nums, int start, int end, int k){ // we need a random number between [start, end] int x = nums[end], i = start; for (int j = start; j < end; j++) { // the num at left should be less than or equal to end if (nums[j] <= x) { swap(nums[j], nums[i++]); } } swap(nums[i], nums[end]); // there are i - start + 1 numbers less than or equal to x // there are end - i numbers larger than x int numLarger = end - i; if (k == numLarger + 1) { return x; } // k is bigger than numLarger + 1, then we need to find it in the left side if (k > numLarger + 1) { returnfind(nums, start, i - 1, k - numLarger - 1); } else { returnfind(nums, i + 1, end, k); } } };
1 2 3 4 5 6 7 8 9 10 11 12 13
classSolution { public: intfindKthLargest(vector<int>& nums, int k){ priority_queue<int, vector<int>, greater<int>> pq; for (int num : nums) { pq.push(num); if (pq.size() > k) { pq.pop(); } } return pq.top(); } };