-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathP215.cpp
51 lines (47 loc) · 998 Bytes
/
P215.cpp
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
42
43
44
45
46
47
48
49
50
51
#include <bits/stdc++.h>
#include "header.h"
using namespace std;
class Solution {
public:
int findKthLargest(vector<int>& nums, int k) {
return findK(nums, k, 0, nums.size()-1);
}
int findK(vector<int>& nums, int k, int l, int r)
{
int pivot = l + (r-l)/2;
swap(nums[r], nums[pivot]);
int i,j;
i = j = l;
while (j<r)
{
if (nums[j] > nums[r])
{
swap(nums[i], nums[j]);
i++;
}
j++;
}
swap(nums[i], nums[j]);
if (i<k-1)
{
return findK(nums, k, i+1, r);
}
else if (i>k-1)
{
return findK(nums, k, l, i-1);
}
else
{
return nums[i];
}
}
};
int main()
{
vector<int> nums = {3,2,1,5,6,4};
int k = 2;
nums = {3,2,3,1,2,4,5,5,6};
k = 4;
cout << Solution().findKthLargest(nums, k) << endl;
return 0;
}