forked from iamAnki/CPP-Programs-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathK-th Largest Element.cpp
More file actions
42 lines (31 loc) · 861 Bytes
/
K-th Largest Element.cpp
File metadata and controls
42 lines (31 loc) · 861 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
// Function to find the k'th largest element in an array using min-heap
int findKthLargest(vector<int> const &arr, int k)
{
if (arr.size() < k) {
exit(-1);
}
priority_queue<int, vector<int>, greater<int>> pq(arr.begin(), arr.begin() + k);
// do for remaining array elements
for (int i = k; i < arr.size(); i++)
{
// if the current element is more than the root of the heap
if (arr[i] > pq.top())
{
// Replace root with the current element
pq.pop();
pq.push(arr[i]);
}
}
return pq.top();
}
int main()
{
vector<int> arr = { 7, 4, 6, 3, 9, 1 };
int k = 2;
cout << "k'th largest array element is " << findKthLargest(arr, k);
return 0;
}