215. Kth Largest Element in an Array
Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element.
For example,
Given [3,2,1,5,6,4]
and k = 2, return 5.
Note:
You may assume k is always valid, 1 ≤ k ≤ array's length.
其实如果取巧的话,sort()一下,取第size()-k个元素就可以,也能通过。
class Solution {
public:
int findKthLargest(vector<int>& nums, int k) {
if (nums.size() < k) return -1;
sort(nums.begin(), nums.end());
return nums[nums.size() - k];
}
};
但是,这个题应该是想考察分割分组的有关知识吧,其实就是用快速排序的思想,对于每一个次快速排序的救国结果,我们对比标准值pivot与的下标与k的关系,从而进行分组,对新分组再进行快速排序,依次列推类推,直到标准值pivot的下标等于k时,此时pivot即为所求。
class Solution {
public:
int QSort(vector<int> &a, int low, int high) {
int pivot = a[low];
while (low < high) {
while (a[high] >= pivot&&low < high) high--;
if (low < high) { a[low++] = a[high]; }
while (a[low] <= pivot &&low < high) low++;
if (low < high) { a[high--] = a[low]; }
}
a[low] = pivot;
return low;
}
int QS_find_N_Min(vector<int> &a, int low, int high, int n) {
if (low >= high) return a[low];
else {
int m = QSort(a, low, high);
if (m - low + 1 < n) return QS_find_N_Min(a, m + 1, high, n - m + low - 1);
else if (m - low + 1 > n) return QS_find_N_Min(a, low, m - 1, n);
else return a[m];
}
}
int findKthLargest(vector<int>& nums, int k) {
if (nums.size() < k) return -1;
return QS_find_N_Min(nums, 0, nums.size()-1, nums.size()-k+1);
}
};