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.
基本思路:
用快排的划分。
选定一个pivot,作一次划分,就能确定pivot的实际位置。
然后以此位置和目标位置作比较。逐步缩小范围。
下面划分的代码,是模仿严蔚敏演示的步骤。比较易懂易记。
既,
1.先取左端点作pivot,取出值后,该位置可视为待填充位置。
2. 在右边寻求第一个不满足条件的点,即大于pivot的值。 将该值赋于步骤1所得到的空闲位置处。 则此位置成为新的待填充位置。
3. 再从左边寻找第一个不满足条件的点,即小于pivot的值。将该值赋于步骤2所得的空间位置处。
重复步骤2和3.
class Solution {
public:
int findKthLargest(vector<int>& nums, int k) {
--k;
int start = 0, stop = nums.size()-1;
while (start < stop) {
int pivot = nums[start];
int i = start, j = stop;
while (i < j) {
while (i < j && nums[j] <= pivot) --j;
if (i == j) break;
nums[i] = nums[j];
++i;
while (i < j && nums[i] >= pivot) ++i;
if (i == j) break;
nums[j] = nums[i];
--j;
}
nums[i] = pivot;
if (i == k)
return pivot;
else if (k < i)
stop = i-1;
else
start = i+1;
}
return nums[start];
}
};
将划分的代码略改进一下:
class Solution {
public:
int findKthLargest(vector<int>& nums, int k) {
--k;
int start = 0, stop = nums.size()-1;
while (start < stop) {
int pivot = nums[start];
int i = start, j = stop;
while (i <= j) {
while (i<=j && nums[j] < pivot) --j;
while (i<=j && nums[i] >= pivot) ++i;
if (i<j)
swap(nums[i], nums[j]);
}
swap(nums[start], nums[j]);
i = j;
if (i == k)
return pivot;
else if (k < i)
stop = i-1;
else
start = i+1;
}
return nums[start];
}
};