-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path215. Kth Largest Element in an Array.cpp
49 lines (44 loc) · 1.53 KB
/
215. Kth Largest Element in an Array.cpp
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
class Solution {
public:
int findKthLargest(vector<int>& nums, int k) {
/*** priority_queue<data_type, container, comparator func>; ***/
/******************************************************
// Max Heap Solution
// SC : O(n)
// Tc : O(n + K*log(n))
priority_queue<int> maxq(nums.begin(), nums.end());
while(--k) maxq.pop();
return maxq.top();
********************************************************/
/*********************************************************
// MIN Heap Solution
// Space - O(K)
// Time - O(n*logK)
priority_queue<int, vector<int>, greater<int> > minq;
for(int i: nums) {
if(minq.size() < k) minq.push(i);
else {
if(minq.top() < i) {
minq.pop();
minq.push(i);
}
}
}
return minq.top();
*****************************************************************/
/***************************************************************/
// MIN Heap Solution without Comparison
// Space - O(K + 1)
// Time - O(n*logK)
priority_queue<int, vector<int>, greater<int> > minq;
for(int i: nums) {
if(minq.size() < k) minq.push(i);
else {
minq.push(i);
minq.pop();
}
}
return minq.top();
/***************************************************************/
}
};