File tree Expand file tree Collapse file tree 1 file changed +44
-0
lines changed
data-structures/Priority_Queues Expand file tree Collapse file tree 1 file changed +44
-0
lines changed Original file line number Diff line number Diff line change
1
+ #include < bits/stdc++.h>
2
+ using namespace std ;
3
+
4
+ /*
5
+
6
+ Given an array A of random integers and an integer k, find and return the kth largest element in the array.
7
+
8
+ */
9
+
10
+ int kthLargest (vector<int > arr, int n, int k){
11
+
12
+ priority_queue<int , vector<int >, greater<int >> pq;
13
+
14
+ for (int i = 0 ; i < k; i++) {
15
+ pq.push (arr[i]);
16
+ }
17
+
18
+ for (int i = k; i < n; i++) {
19
+ int val = pq.top ();
20
+ if (arr[i] > val) {
21
+ pq.pop ();
22
+ pq.push (arr[i]);
23
+ }
24
+ }
25
+
26
+ return pq.top ();
27
+
28
+ }
29
+
30
+ int main () {
31
+ int n, k, s;
32
+ vector<int > arr;
33
+ cin >> n;
34
+
35
+ for (int i = 0 ; i < n; i++) {
36
+ cin >> s;
37
+ arr.push_back (s);
38
+ }
39
+
40
+ cin >> k;
41
+ cout << kthLargest (arr, n, k) << endl;
42
+ }
43
+
44
+
You can’t perform that action at this time.
0 commit comments