-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathkthLargestElem.cpp
More file actions
41 lines (39 loc) · 911 Bytes
/
Copy pathkthLargestElem.cpp
File metadata and controls
41 lines (39 loc) · 911 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
/**
* https://leetcode.com/problems/kth-largest-element-in-an-array/
* Array, Divide and Conquer, Sorting, Priority queue, Quickselect
* Medium
*/
#include <iostream>
#include <queue>
using namespace std;
class Solution {
public:
int findKthLargest(vector<int>& nums, int k) {
priority_queue<int> max_heap;
for (int num : nums) {
max_heap.push(num);
}
for (int i = 0; i < k - 1; i++) {
max_heap.pop();
}
return max_heap.top();
}
};
int main() {
vector<int> nums;
int k, numsSize;
cout << "Input nums array size: ";
cin >> numsSize;
int num;
cout << "Input array" << endl;
while (numsSize) {
cin >> num;
nums.push_back(num);
numsSize--;
}
cout << "Input K: ";
cin >> k;
Solution solution;
int kthLargest = solution.findKthLargest(nums, k);
cout << "k-th largest element in array: " << kthLargest << endl;
}