-
Notifications
You must be signed in to change notification settings - Fork 0
/
kth largest element.cpp
63 lines (44 loc) · 1.38 KB
/
kth largest 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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
//Quick Select approach
class Solution {
public:
int partition_algo(vector<int>& nums, int L, int R) {
int P = nums[L];
int i = L+1; //0
int j = R; //0
while(i <= j) {
if(nums[i] < P && nums[j] > P) {
swap(nums[i], nums[j]);
i++;
j--;
}
if(nums[i] >= P) {
i++;
}
if(nums[j] <= P) {
j--;
}
}
swap(nums[L], nums[j]);
return j; //P is at jth index
}
int findKthLargest(vector<int>& nums, int k) {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int n = nums.size();
int L = 0;
int R = n-1;
int pivot_idx = 0;
//kth largest pivot element - nums[k-1] (descendinforder me partition karenge)
while(true) {
pivot_idx = partition_algo(nums, L, R);
if(pivot_idx == k-1) {
break;
} else if(pivot_idx > k-1) { //2nd larget , 4th larget
R = pivot_idx - 1;
} else {
L = pivot_idx + 1;
}
}
return nums[pivot_idx];
}
};