forked from fineanmol/Hacktoberfest2026
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKth Largest in Array.cpp
More file actions
49 lines (38 loc) · 1022 Bytes
/
Copy pathKth Largest in Array.cpp
File metadata and controls
49 lines (38 loc) · 1022 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
43
44
45
46
47
48
49
// Q70 https://leetcode.com/problems/kth-largest-element-in-an-array/
//BETTER
// https://classroom.codingninjas.com/app/classroom/me/6855/content/92022/offering/1027938/problem/1641
#include<queue>
int kthLargest(int* arr, int n, int k) {
// Write your code here
priority_queue<int,vector<int>,greater<int>> p;
int i;
for(i=0;i<k;i++){
p.push(arr[i]);
}
for(i; i<n;i++){
if(arr[i]>p.top()){
p.pop();
p.push(arr[i]);
}
}
return p.top();
}
// https://leetcode.com/problems/kth-largest-element-in-an-array/
class Solution {
public:
int findKthLargest(vector<int>& nums, int k) {
int n=nums.size();
if(n==0)
return -1;
priority_queue<int> pq;
// priority_queue<int,vector<int>,greater<int>> pq; MIN HEAP
for(auto i: nums)
pq.push(i);
int res=INT_MIN;
while(k--){
res=pq.top();
pq.pop();
}
return res;
}
};