π Problem Details
- Title:
215. Kth Largest Element in an Array
- Link: https://leetcode.com/problems/kth-largest-element-in-an-array/
- Difficulty: Medium
- Tags/Categories: Priority-Queue
input array
nums
input integerk
return the kth largest element in the array follow up: can you do this without sorting?
πWhat Were My Initial Thoughts?
trivial approach would be to sort the array in descending order and return the k-1th element
class Solution {
public:
Β Β int findKthLargest(vector<int>& nums, int k) {
Β Β Β Β sort(nums.begin(), nums.end(), greater<int>());
Β Β Β Β return nums[k - 1];
Β Β }
};
a more optimized approach could be to use a priority queue or min heap
we keep a min-heap of fixed size k
when the heap exceeds this size we pop
π‘ Explanation of Solution
- Initialize a min-heapΒ
heap
. - Iterate over the input. For eachΒ
num
:- PushΒ
num
Β onto the heap. - If the size ofΒ
heap
Β exceedsΒk
, pop fromΒheap
.
- PushΒ
- Return the top of theΒ
heap
.
β Complexity Analysis
Time Complexity: O(n log k)
- the limited size of the heap being of size k makes it more efficient than a traditional sort
Space Complexity: O(k)
π» Implementation of Solution
class Solution {
public:
int findKthLargest(vector<int>& nums, int k) {
priority_queue<int> pq;
for(int num : nums) {
pq.push(-num);
if(pq.size() > k) {
pq.pop();
}
}
return -pq.top();
}
};