0%

LeetCode: Kth Largest Element in an Array

徒手裸写快排

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
30
31
32
33
34
35
36
37
38
39
40
41
class Solution {
public:
int findKthLargest(vector<int>& nums, int k) {
return bar(nums, 0, nums.size() - 1, k - 1);
}

int foo(vector<int> &nums, int left, int right)
{
if (left > right)
return -1;

if (left == right)
return 0;

int temp = nums[right];
int p = left, q = right - 1;
while (p != q)
{
while (p != q && nums[p] > temp)
++p;
while (p != q && nums[q] <= temp)
--q;
if (p != q)
swap(nums[p], nums[q]);
}
if (nums[p] < nums[right])
swap(nums[p], nums[right]);
return p - left;
}

int bar(vector<int> &nums, int left, int right, int k)
{
int t = foo(nums, left, right);
if (k == t)
return nums[left+t];
else if (k < t)
return bar(nums, left, left + t, k);
else
return bar(nums, left + t + 1, right, k - t - 1);
}
};