|
1 |
| -use rand::Rng; |
2 |
| - |
3 | 1 | 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]; |
7 | 11 | }
|
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; |
15 | 20 | }
|
16 |
| - } |
17 |
| - nums.swap(l, mark); |
18 | 21 |
|
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 | + } |
22 | 26 |
|
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 | + } |
28 | 38 | }
|
29 | 39 | }
|
0 commit comments