forked from sarthakd999/Hacktoberfest2021-2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path#1_Kth_smallest_element.cpp
48 lines (44 loc) · 1.09 KB
/
#1_Kth_smallest_element.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
/*
TODO: Kth smallest element
? https://practice.geeksforgeeks.org/problems/kth-smallest-element5635/1
*/
#include "bits/stdc++.h"
using namespace std;
//! heap method Optimal
class Solution{
public:
int kthSmallest(int arr[], int l, int r, int k) {
priority_queue<int> pq;
for(int i=l;i<=r;i++) {
pq.push(arr[i]);
if(pq.size() > k) pq.pop();
}
return pq.top();
}
};
//! shorting method
class Solution{
public:
int kthSmallest(int arr[], int l, int r, int k) {
vector<int> ans;
for(int i=l;i<=r;i++) ans.push_back(arr[i]);
sort(ans.begin(),ans.end());
k--;
return ans[k];
}
};
//! heap method Bute TLE
class Solution{
public:
int kthSmallest(int arr[], int l, int r, int k) {
priority_queue<int,vector<int>,greater<>> pq;
for(int i=l;i<=r;i++) pq.push(arr[i]);
if(pq.size() < k) return -1;
int ans = 0;
while(k-- and !pq.empty()) {
ans = pq.top();
pq.pop();
}
return ans;
}
};