215. Kth Largest Element in an Array
Find the k th largest element in an unsorted array. Note that it is the k th 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大的数字,最朴素的想法就是我先把数组排好序,然后直接取第k大的数字就行了。可是排序最快也需要O(nlog(n))的时间复杂度,并且部门并不需要所有的数字都排好序。因此,我们可以借鉴快排的思想去解决这道题。
- 取第一个元素作为pivot,与后面的数字进行比较。
- 如果遇到比pivot小的数字,就将该数字放到pivot的右边,如果比pivot大的数字, 就放在pivot左边。
- 重复过程(2)
- 对比pivot的下标和k值,如果等于k值,则找到第k大的数字,如果小于k值,则在pivot的右边找第k - l.length()大的数字,如果大于k值,则在pivot的左边找第k大的数字。
代码:
class Solution {
public:
int findKthLargest(vector<int>& nums, int k) {
int start = 0, end = nums.size() - 1;
while (true) {
int largeIndex = findKthLargestRec(nums, start, end);
if (largeIndex == k - 1) return nums[largeIndex];
if (largeIndex > k - 1) end = largeIndex - 1;
else start = largeIndex + 1;
}
}
int findKthLargestRec(vector<int>& nums, int start, int end) {
int pivot = nums[start];
int s = start + 1, e = end;
while (s <= e) {
if (nums[s] < pivot && nums[e] > pivot)
swap(nums[s++], nums[e--]);
if (nums[s] >= pivot) s++;
if (nums[e] <= pivot) e--;
}
swap(nums[start], nums[e]);
return e;
}
};

887

被折叠的 条评论
为什么被折叠?



