sort the array and pick the kth
O(Nlog(N))
Use size k min heap
class Solution {
public:
int findKthLargest(vector<int>& nums, int k) {
priority_queue<int, vector<int> ,greater<int>> pq;
for(auto n : nums){
pq.push(n);
if (pq.size() > k)
pq.pop();
}
return pq.top();
}
};
We use a min heap of size k to filter through all elements and if after adding an element to heap causing the heap size to exceed k, then we pop it.
This algorithm will eventually contain the kth largest element since all elements smaller than kth largest elem will be at the internal or leaf. And any node larger than kth largest will eventually be at the top and get pop off.