Skip to content

Commit f0785f5

Browse files
authored
Update Solution.rs
1 parent 1a4dfef commit f0785f5

File tree

1 file changed

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

1 file changed

+32
-22
lines changed
Lines changed: 32 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,29 +1,39 @@
1-
use rand::Rng;
2-
31
impl Solution {
4-
fn sort(nums: &mut Vec<i32>, l: usize, r: usize, k: usize) {
5-
if l + 1 > k || l >= r {
6-
return;
2+
pub fn find_kth_largest(mut nums: Vec<i32>, k: i32) -> i32 {
3+
let len = nums.len();
4+
let k = len - k as usize;
5+
Self::quick_sort(&mut nums, 0, len - 1, k)
6+
}
7+
8+
fn quick_sort(nums: &mut Vec<i32>, l: usize, r: usize, k: usize) -> i32 {
9+
if l == r {
10+
return nums[l];
711
}
8-
nums.swap(l, rand::thread_rng().gen_range(l, r));
9-
let num = nums[l];
10-
let mut mark = l;
11-
for i in l..r {
12-
if nums[i] > num {
13-
mark += 1;
14-
nums.swap(i, mark);
12+
13+
let (mut i, mut j) = (l as isize - 1, r as isize + 1);
14+
let x = nums[(l + r) / 2];
15+
16+
while i < j {
17+
i += 1;
18+
while nums[i as usize] < x {
19+
i += 1;
1520
}
16-
}
17-
nums.swap(l, mark);
1821

19-
Self::sort(nums, l, mark, k);
20-
Self::sort(nums, mark + 1, r, k);
21-
}
22+
j -= 1;
23+
while nums[j as usize] > x {
24+
j -= 1;
25+
}
2226

23-
pub fn find_kth_largest(mut nums: Vec<i32>, k: i32) -> i32 {
24-
let n = nums.len();
25-
let k = k as usize;
26-
Self::sort(&mut nums, 0, n, k);
27-
nums[k - 1]
27+
if i < j {
28+
nums.swap(i as usize, j as usize);
29+
}
30+
}
31+
32+
let j = j as usize;
33+
if j < k {
34+
Self::quick_sort(nums, j + 1, r, k)
35+
} else {
36+
Self::quick_sort(nums, l, j, k)
37+
}
2838
}
2939
}

0 commit comments

Comments
 (0)