题目:
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.
解答:
这道题《编程之美》上有着详细的探讨。最快的方法就是类似快速排序(Quick Sorting),每次将大于 key 的部分与小于 key 的部分区分出来。
如果小于 key 的个数大于 K,则不再寻找大于 key 的部分;如果小于 key 的个数小于 K,则寻找大于 key 的数中第(K - 小于 K 个数)大的数。
这样,每次大约有一半数字不需要寻找,时间复杂度约为O(n + n/2 + n/4 + .. + 1)= O(2n)= O(n).
最后,需要注意:快速排序、二分排序这一类,二分(递归)的子问题中应该去除中间元素(每次缩小范围,防止范围不变而死循环)。
class Solution {
public:
void swap(int& a, int&b) {
int tmp = a;
a = b;
b = tmp;
}
int findKthLargest(vector<int>& nums, int k) {
int head = 0;
int tail = nums.size() - 1;
int index = 0;
while(head < tail) {
while(nums[tail] <= nums[index] && head < tail) tail--;
swap(nums[tail], nums[index]);
index = tail;
while(nums[head] >= nums[index] && head < tail) head++;
swap(nums[head], nums[index]);
index = head;
}
if(k == index + 1) return nums[index];
else if(k < index + 1) {
vector<int> sub(nums.begin(), nums.begin() + index);
return findKthLargest(sub, k);
}
else if(k > index + 1) {
vector<int> sub(nums.begin() + index + 1, nums.end());
return findKthLargest(sub, k - index - 1);
}
}
};