forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0215-kth-largest-element-in-an-array.cpp
95 lines (85 loc) · 2.34 KB
/
0215-kth-largest-element-in-an-array.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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
/*
Given array and int k, return kth largest element in array
Ex. nums = [3,2,1,5,6,4], k = 2 -> 5
Quickselect, partition until pivot = k, left side all > k
Time: O(n) -> optimized from O(n log k) min heap solution
Space: O(1)
*/
// class Solution {
// public:
// int findKthLargest(vector<int>& nums, int k) {
// priority_queue<int, vector<int>, greater<int>> pq;
// for (int i = 0; i < nums.size(); i++) {
// pq.push(nums[i]);
// if (pq.size() > k) {
// pq.pop();
// }
// }
// return pq.top();
// }
// };
/*
class Solution {
public:
int findKthLargest(vector<int>& nums, int k) {
int low = 0;
int high = nums.size() - 1;
int pivotIndex = nums.size();
while (pivotIndex != k - 1) {
pivotIndex = partition(nums, low, high);
if (pivotIndex < k - 1) {
low = pivotIndex + 1;
} else {
high = pivotIndex - 1;
}
}
return nums[k - 1];
}
private:
int partition(vector<int>& nums, int low, int high) {
int pivot = nums[low];
int i = low + 1;
int j = high;
while (i <= j) {
if (nums[i] < pivot && pivot < nums[j]) {
swap(nums[i], nums[j]);
i++;
j--;
}
if (nums[i] >= pivot) {
i++;
}
if (pivot >= nums[j]) {
j--;
}
}
swap(nums[low], nums[j]);
return j;
}
};
*/
// Video's QuickSelect implementation
class Solution {
public:
int findKthLargest(vector<int>& nums, int k) {
int index = nums.size() - k;
return quickSelect(nums, index, 0, nums.size() - 1);
}
private:
int quickSelect(vector<int>& nums, int k, int l, int r){
int pivot = nums[r];
int p_pos = l;
for (int i = l; i < r; ++i){
if (nums[i] <= pivot){
swap(nums[i], nums[p_pos]);
++p_pos;
}
}
swap(nums[p_pos], nums[r]);
if (k < p_pos)
return quickSelect(nums, k, l, p_pos - 1);
if (k > p_pos)
return quickSelect(nums, k, p_pos + 1, r);
return nums[p_pos];
}
};