题目:
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.
题意:
找出数组中第k大的元素。
思路:
可以采用partition方法,partition的算法是求出以某个元素作为划分,该元素之前的元素都小于其,该元素之后的元素都大于等于其大小。
所以可以递归的查找该元素所在的位置。如果这次partition前面的元素等于nums.size() - k +1,则返回这个元素。如果这次partition前面的元素的个数小于nums.size() - k +1那么继续递归在后面的部分。否则递归前面的部分。
以上。
代码如下:
class Solution {
public:
int findKthLargest(vector<int>& nums, int k) {
int index = partition(nums, 0, nums.size() - 1, nums.size() - k + 1);
return nums[index];
}
int partition(vector<int>& nums, int begin, int end, int has) {
int i = begin;
int p = nums[begin];
for(int j = begin + 1; j <= end; j++) {
if(nums[j] < p) {
i++;
swap(nums[i], nums[j]);
}
}
swap(nums[begin], nums[i]);
has -= (i - begin);
if(has == 1)return i;
else if(has < 1) return partition(nums, begin, i - 1, has + (i - begin));
else return partition(nums, i + 1, end, has - 1);
}
};