-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathKth_Largest_Element.cpp
49 lines (46 loc) · 1.26 KB
/
Kth_Largest_Element.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
/*
Find K-th largest element in an array.
Note
You can swap elements in the array
Example
In array [9,3,2,4,8], the 3th largest element is 4
*/
#include<vector>
#include <stdlib.h>
using namespace std;
class Solution {
public:
//param k : description of k
//param a : description of array and index 0 ~ n-1
//return: description of return
int kthLargestElement(int k, vector<int> a) {
return kthLargestElement(k, a, 0, a.size() - 1);
}
int kthLargestElement(int k, vector<int>& a, int begin, int end) {
if (begin == end) {
return a[begin];
}
int q = pivot(a, begin, end);
if (q + 1 == k) {
return a[q];
} else if (q + 1 > k) {
kthLargestElement(k, a, begin, q - 1);
} else {
kthLargestElement(k, a, q + 1, end);
}
}
int pivot(vector<int>& a, int begin, int end) {
int pivotIndex = begin + (rand() % (end - begin + 1));
int pivot = a[pivotIndex];
swap(a[pivotIndex], a[begin]);
int i = begin, j, temp;
for (j = begin + 1; j <= end; j++) {
if (a[j] > pivot) {
i++;
swap(a[i], a[j]);
}
}
swap(a[i], a[begin]);
return i;
}
};