[LeetCode]215. Kth Largest Element in an Array
partition算法运行时间依然为 O(n),quickSortK 只需要找到第 k 大的元素,因此最差情况下 quickSortK 需要排序前 k 个元素,递归树深度最大为 log(k),算法整体运行时间为 O(n logk)
class Solution {
public:
int findKthLargest(vector<int>& nums, int k) {
return quickSortK(nums, nums.begin(), nums.end(), k);
}
private:
int quickSortK(vector<int>&, vector<int>::iterator, vector<int>::iterator,
const int k);
vector<int>::iterator partition(vector<int>&, vector<int>::iterator,
vector<int>::iterator);
void exchange(vector<int>::iterator, vector<int>::iterator);
};
int Solution::quickSortK(vector<int>& nums, vector<int>::iterator begin,
vector<int>::iterator end, const int k) {
if (end - begin <= 1) return *begin;
auto mid = partition(nums, begin, end);
if (nums.end() - mid == k)
return *mid;
else if (nums.end() - mid < k)
return quickSortK(nums, begin, mid, k);
else
return quickSortK(nums, mid + 1, end, k);
}
vector<int>::iterator Solution::partition(vector<int>& nums,
vector<int>::iterator begin,
vector<int>::iterator end) {
if (end - begin <= 1) return begin;
int key = *begin;
auto less = begin, ori = begin;
begin += 1;
while (begin != end) {
if (*begin < key) {
exchange(++less, begin);
}
begin++;
}
exchange(ori, less);
return less;
}
void Solution::exchange(vector<int>::iterator i1, vector<int>::iterator i2) {
int temp = *i1;
*i1 = *i2;
*i2 = temp;
}