[leetcode]Kth Largest Element in an Array
链接:https://leetcode.com/problems/kth-largest-element-in-an-array/description/
Question
Find the **k**th largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element.
Example 1
Input: [3,2,1,5,6,4] and k = 2
Output: 5
Example 2
Input: [3,2,3,1,2,4,5,5,6] and k = 4
Output: 4
Note:
You may assume k is always valid, 1 ≤ k ≤ array's length.
Solution
class Solution {
public:
vector<int> nums;
int partition(int left, int right) {
int x = nums[left];
int i = left, j = right;
while (i < j) {
while (i < j && nums[j] < x) j--;
nums[i] = nums[j];
while (i < j && nums[i] >= x) i++;
nums[j] = nums[i];
}
// 记得还原回去
nums[i] = x;
return i;
}
int quickselect(int left, int right, int k) {
int index = partition(left, right);
if (index == k) return nums[k];
else if (index > k) return quickselect(left, index-1, k);
else return quickselect(index+1, right, k); // 这里不需要对k改变什么,因为left和right的值就是全局的
}
int findKthLargest(vector<int>& nums, int k) {
this->nums = nums;
return quickselect(0, nums.size()-1, k-1);
}
};
思路:借鉴了快速排序的思想,通过partition来确定某一个基准数的位置。根据这个基准数的index来确定对前面还是后面进行进一步选择。需要注意k的值在递归过程中是保持不变的,因为这个索引是在全局中的。