K-th largest element in array

题目

https://leetcode.com/problems/kth-largest-element-in-an-array/description/

-w950

想法

可以说是非常经典的题目了。

基本是,快排的划分思想,但是,不用全拍完,判断与k的大小关系,选择性的排一边就好,所以时间复杂度应该是O(n),空间复杂度为O(1).

答案

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class Solution {
private:
int partition(vector<int>& nums, int l, int r) {
int pivot = nums[l];
while (l < r) {
while (l < r && nums[r] <= pivot)
r--;
nums[l] = nums[r];
while (l < r && nums[l] >= pivot)
l++;
nums[r] = nums[l];
}
nums[l] = pivot;
return l;
}
public:
int findKthLargest(vector<int>& nums, int k) {
int left = 0, right = nums.size() - 1;
while (true) {
int mid = partition(nums, left, right);
if (mid == k - 1)
return nums[mid];
if (mid < k - 1)
left = mid + 1;
else
right = mid - 1;
}
}
};