forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main2.cpp
51 lines (39 loc) · 1.07 KB
/
main2.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
50
51
/// Source : https://leetcode.com/problems/kth-largest-element-in-an-array/
/// Author : liuyubobobo
/// Time : 2018-01-07
#include <iostream>
#include <vector>
#include <cassert>
#include <stdexcept>
#include <ctime>
#include <queue>
using namespace std;
/// Using Min Heap to store the k largest elements
/// Time Complexity: O(nlogk)
/// Space Complexity: O(k)
class Solution {
public:
int findKthLargest(vector<int>& nums, int k) {
priority_queue<int, vector<int>, greater<int>> pq;
for(int e: nums)
if(pq.size() != k)
pq.push(e);
else if(e > pq.top()){
pq.pop();
pq.push(e);
}
return pq.top();
}
};
int main() {
vector<int> nums1 = {3, 2, 1, 5, 6, 4};
cout << Solution().findKthLargest(nums1, 2) << endl;
// 5
vector<int> nums2 = {3, 1, 2, 4};
cout << Solution().findKthLargest(nums2, 2) << endl;
// 3
vector<int> nums3 = {3, 3, 3, 3, 3, 3, 3, 3, 3};
cout << Solution().findKthLargest(nums3, 8) << endl;
// 3
return 0;
}