Skip to content

Commit ecba19c

Browse files
rust: kth largest element
1 parent fd64f03 commit ecba19c

File tree

1 file changed

+85
-0
lines changed
  • rust/algorithms/others/kth_largest_element_nov_5_2024

1 file changed

+85
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
use std::collections::BinaryHeap;
2+
3+
/// Given an integer array nums and an integer k, return the kth largest element in the array.
4+
///
5+
/// Note that it is the kth largest element in the sorted order, not the kth distinct element.
6+
///
7+
/// Can you solve it without sorting?
8+
///
9+
/// Example 1:
10+
///
11+
/// Input: nums = [3,2,1,5,6,4], k = 2
12+
/// Output: 5
13+
/// Example 2:
14+
///
15+
/// Input: nums = [3,2,3,1,2,4,5,5,6], k = 4
16+
/// Output: 4
17+
///
18+
/// Constraints:
19+
///
20+
/// 1 <= k <= nums.length <= 105
21+
/// -104 <= nums[i] <= 104
22+
23+
fn find_kth_largest(nums: Vec<i32>, k: i32) -> i32 {
24+
let mut heap: BinaryHeap<_> = nums.into_iter().collect();
25+
26+
for _ in 0..k as usize - 1 {
27+
let _ = heap.pop();
28+
}
29+
30+
heap.pop().unwrap()
31+
}
32+
33+
fn find_kth_largest_quick_select(nums: Vec<i32>, k: i32) -> i32 {
34+
do_find_kth_largest_quick_select(&nums, 0, nums.len() - 1, k as usize - 1)
35+
}
36+
37+
fn do_find_kth_largest_quick_select(nums: &[i32], start: usize, end: usize, k: usize) -> i32 {
38+
if start == end {
39+
return nums[start];
40+
}
41+
42+
let index = (start + end) / 2;
43+
if index == k {
44+
return nums[index];
45+
}
46+
47+
if k < index {
48+
do_find_kth_largest_quick_select(nums, start, index - 1, k)
49+
} else {
50+
do_find_kth_largest_quick_select(nums, index + 1, end, k)
51+
}
52+
}
53+
54+
fn main() {}
55+
56+
#[cfg(test)]
57+
mod tests {
58+
use quickcheck::quickcheck;
59+
60+
use super::*;
61+
62+
fn check(nums: Vec<i32>, k: usize, f: fn(Vec<i32>, i32) -> i32) -> bool {
63+
if nums.is_empty() {
64+
return true;
65+
}
66+
67+
let k = 1 + k % nums.len();
68+
let mut nums = nums;
69+
nums.sort_unstable();
70+
nums.reverse();
71+
let expected = nums[k - 1];
72+
expected == f(nums, k as i32)
73+
}
74+
75+
quickcheck! {
76+
#[test]
77+
fn test_find_kth_largest(nums: Vec<i32>, k: usize) -> bool {
78+
check(nums, k, find_kth_largest)
79+
}
80+
81+
fn test_find_kth_largest_quick_select(nums: Vec<i32>, k: usize) -> bool {
82+
check(nums, k, find_kth_largest_quick_select)
83+
}
84+
}
85+
}

0 commit comments

Comments
 (0)