-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathkth_largest_element_in_array.cpp
More file actions
49 lines (40 loc) · 1014 Bytes
/
Copy pathkth_largest_element_in_array.cpp
File metadata and controls
49 lines (40 loc) · 1014 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
/*
215. Kth Largest Element in an Array
Medium
Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element.
Example 1:
Input: [3,2,1,5,6,4] and k = 2
Output: 5
Example 2:
Input: [3,2,3,1,2,4,5,5,6] and k = 4
Output: 4
Note:
You may assume k is always valid, 1 ≤ k ≤ array's length.
*/
//Using sorting
class Solution {
public:
static bool custom_sort(int a, int b){
return a>b;
}
int findKthLargest(vector<int>& nums, int k) {
if(nums.size()==0 || k>nums.size())
return -1;
sort(nums.begin(), nums.end(), custom_sort);
return nums[k-1];
}
};
//Max-heap solution
class Solution{
public :
int findKthLargest(vector<int>& nums, int k){
priority_queue<int> maxHeap;
for(int el : nums){
maxHeap.push(el);
}
for(int i=0;i<k-1;i++){
maxHeap.pop();
}
return maxHeap.top();
}
}