From 26ffc40123fe3e72d5fcadcf2162f6d69f783f49 Mon Sep 17 00:00:00 2001 From: jackfiled Date: Sat, 20 Jul 2024 11:42:37 +0800 Subject: [PATCH] 20240720 Finished --- src/problem/mod.rs | 3 +- .../p215_kth_largest_element_in_an_array.rs | 37 +++++++++++++++++++ 2 files changed, 39 insertions(+), 1 deletion(-) create mode 100644 src/problem/p215_kth_largest_element_in_an_array.rs diff --git a/src/problem/mod.rs b/src/problem/mod.rs index 5fe67cd..ae2c84a 100644 --- a/src/problem/mod.rs +++ b/src/problem/mod.rs @@ -178,4 +178,5 @@ mod p35_search_insert_position; mod p74_search_a_2d_matrix; mod p33_search_in_rotated_sorted_array; mod p34_find_first_and_last_position_of_element_in_sorted_array; -mod p153_find_minimum_in_rotated_sorted_array; \ No newline at end of file +mod p153_find_minimum_in_rotated_sorted_array; +mod p215_kth_largest_element_in_an_array; \ No newline at end of file diff --git a/src/problem/p215_kth_largest_element_in_an_array.rs b/src/problem/p215_kth_largest_element_in_an_array.rs new file mode 100644 index 0000000..304d3f0 --- /dev/null +++ b/src/problem/p215_kth_largest_element_in_an_array.rs @@ -0,0 +1,37 @@ +/** + * [215] Kth Largest Element in an Array + */ +pub struct Solution {} + + +// submission codes start here + +impl Solution { + pub fn find_kth_largest(nums: Vec, k: i32) -> i32 { + use std::{cmp::Reverse, collections::BinaryHeap}; + + let k = k as usize; + let mut heap = BinaryHeap::>::with_capacity(k); + + for i in nums { + if heap.len() == k && heap.peek().unwrap().0 < i { + heap.pop(); + heap.push(Reverse(i)); + } else if heap.len() < k { + heap.push(Reverse(i)); + } + } + + heap.pop().unwrap().0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_215() {} +}