Leetcode 215. Kth Largest Element in an Array
Given an integer array nums
and an integer k
, return the k
th largest element in the array.
Note that it is the k
th largest element in the sorted order, not the k
th distinct element.
Input: nums = [3,2,1,5,6,4], k = 2
Output: 5
Input: nums = [3,2,3,1,2,4,5,5,6], k = 4
Output: 4
1 <= k <= nums.length <= 10^4
-10^4 <= nums[i] <= 10^4
Q: Can the input array contain duplicate elements? A: Yes, the input array can contain duplicate elements.
Q: Are the elements in the array always integers? A: Yes, all elements in the array are integers.
Q: Is k
always a valid index within the range of the array?
A: Yes, k
is always within the valid range as per the constraints given.
To solve the problem of finding the k
th largest element, we can use one of the following approaches:
(k-1)
-th index. This is straightforward but might not be the most efficient way.k
to keep track of the k
largest elements.k
. At the end, the root of the heap will be the k
th largest element.Given the constraints, using a Min-Heap seems to be a balanced approach in terms of implementation complexity and efficiency.
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
class Solution {
public:
int findKthLargest(vector<int>& nums, int k) {
// Min-heap to store the k largest elements
priority_queue<int, vector<int>, greater<int>> minHeap;
for (int num : nums) {
minHeap.push(num);
// Keep the heap size to k
if (minHeap.size() > k) {
minHeap.pop();
}
}
// The root of the heap is the k-th largest element
return minHeap.top();
}
};
// Driver code for testing
int main() {
Solution solution;
vector<int> nums1 = {3,2,1,5,6,4};
int k1 = 2;
cout << "The " << k1 << "-th largest element in the first array is: " << solution.findKthLargest(nums1, k1) << endl;
vector<int> nums2 = {3,2,3,1,2,4,5,5,6};
int k2 = 4;
cout << "The " << k2 << "-th largest element in the second array is: " << solution.findKthLargest(nums2, k2) << endl;
return 0;
}
k
takes O(log k) and we do this for all n
elements.This method efficiently finds the k
th largest element while managing the input constraints effectively.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?