-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSource.cpp
More file actions
45 lines (38 loc) · 867 Bytes
/
Source.cpp
File metadata and controls
45 lines (38 loc) · 867 Bytes
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
class Solution {
public:
/*
* param k : description of k
* param nums : description of array and index 0 ~ n-1
* return: description of return
*/
int kthLargestElement(int k, vector<int> nums) {
return helper(nums, 0, nums.size() - 1, nums.size() - k + 1);
}
int helper(vector<int> &nums, int left, int right, int k) {
if (left == right) {
return nums[left];
}
int i = left, j = right;
int pivot = nums[(i + j) / 2];
while (i <= j) {
while (i <= j && nums[i] < pivot) {
i++;
}
while (i <= j && nums[j] > pivot) {
j--;
}
if (i <= j) {
swap(nums[i], nums[j]);
i++;
j--;
}
}
if (left + k - 1 <= j) {
return helper(nums, left, j, k);
}
if (left + k - 1 < i) {
return nums[left + k - 1];
}
return helper(nums, i, right, k - (i - left));
}
};