Skip to content

Commit 76dd4eb

Browse files
authored
Update Solution.cpp
1 parent ff0882c commit 76dd4eb

File tree

1 file changed

+23
-16
lines changed
  • solution/0200-0299/0215.Kth Largest Element in an Array

1 file changed

+23
-16
lines changed

solution/0200-0299/0215.Kth Largest Element in an Array/Solution.cpp

Lines changed: 23 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -2,20 +2,27 @@ class Solution {
22
public:
33
int findKthLargest(vector<int>& nums, int k) {
44
int n = nums.size();
5-
return quickSort(nums, 0, n - 1, n - k);
5+
k = n - k;
6+
auto quickSort = [&](auto&& quickSort, int l, int r) -> int {
7+
if (l == r) {
8+
return nums[l];
9+
}
10+
int i = l - 1, j = r + 1;
11+
int x = nums[(l + r) >> 1];
12+
while (i < j) {
13+
while (nums[++i] < x) {
14+
}
15+
while (nums[--j] > x) {
16+
}
17+
if (i < j) {
18+
swap(nums[i], nums[j]);
19+
}
20+
}
21+
if (j < k) {
22+
return quickSort(quickSort, j + 1, r);
23+
}
24+
return quickSort(quickSort, l, j);
25+
};
26+
return quickSort(quickSort, 0, n - 1);
627
}
7-
8-
int quickSort(vector<int>& nums, int left, int right, int k) {
9-
if (left == right) return nums[left];
10-
int i = left - 1, j = right + 1;
11-
int x = nums[left + right >> 1];
12-
while (i < j) {
13-
while (nums[++i] < x)
14-
;
15-
while (nums[--j] > x)
16-
;
17-
if (i < j) swap(nums[i], nums[j]);
18-
}
19-
return j < k ? quickSort(nums, j + 1, right, k) : quickSort(nums, left, j, k);
20-
}
21-
};
28+
};

0 commit comments

Comments
 (0)