Quick Select
Implementation
// OJ: https://leetcode.com/problems/kth-largest-element-in-an-array/
// Author: github.com/lzl124631x
// Time: O(N) on averge, O(N^2) in the worst case
// Space: O(1)
class Solution {
int partition(vector<int> &A, int L, int R) {
int i = L, pivotIndex = L + rand() % (R - L + 1), pivot = A[pivotIndex];
swap(A[pivotIndex], A[R]);
for (int j = L; j < R; ++j) {
if (A[j] < pivot) swap(A[i++], A[j]);
}
swap(A[i], A[R]);
return i;
}
public:
int findKthLargest(vector<int>& A, int k) {
int L = 0, R = A.size() - 1;
k = A.size() - k + 1;
while (true) {
int M = partition(A, L, R);
if (M + 1 == k) return A[M];
if (M + 1 > k) R = M - 1;
else L = M + 1;
}
}
};Reference
Problems
Last updated