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
.
題意
找到一個無序數(shù)組中第k大的數(shù)。
分析
類似快速排序一樣。每層遞歸中,對當(dāng)前的nums區(qū)段內(nèi)的元素進(jìn)行操作:
- 保存當(dāng)前區(qū)段的第一個元素
nums[bottom]
為save
。 - 類似快排,將大于
save
的元素移到左側(cè),小于save
的移到右側(cè)。 - 通過下標(biāo)相減得知
save
在當(dāng)前區(qū)段中的次序rank
。 - 如
rank == k
,則save就是第k大的數(shù)。 - 如
rank < k
,則第k大的數(shù)在save所在位置的右側(cè),進(jìn)入下一層遞歸。 - 如
rank > k
,則第k大的數(shù)在save所在位置的左側(cè),進(jìn)入下一層遞歸。
AC代碼
class Solution {
public:
int answer;
int findKthLargest(vector<int>& nums, int k) {
find(nums, 0, nums.size() - 1, k);
return answer;
}
void find(vector<int>& nums, int bottom, int top, int k) {
int i = bottom, j = top, save = nums[bottom];
while (i < j) {
for (; i < j && nums[j] <= save; --j);
nums[i] = nums[j];
for (; i < j && nums[i] >= save; ++i);
nums[j] = nums[i];
}
int rank = j - bottom + 1;
if (rank == k) {
answer = save; return;
}
if (rank > k) {
find(nums, bottom, j - 1, k);
} else {
find(nums, j + 1, top, k - rank);
}
}
};