Skip to content

Commit

Permalink
Added kth largest element solution
Browse files Browse the repository at this point in the history
  • Loading branch information
jusexton committed Dec 23, 2023
1 parent 68a91ff commit 4812419
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,7 @@ other languages.
- Authentication Manager (https://leetcode.com/problems/design-authentication-manager/)
- Best Time to Buy and Sell Stock (https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii)
- Longest Substring Without Repeating Characters (https://leetcode.com/problems/longest-substring-without-repeating-characters/)
- Kth Largest Element (https://leetcode.com/problems/kth-largest-element-in-an-array/)

### Other

Expand Down
28 changes: 28 additions & 0 deletions src/leetcode/kth_largest_element.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
use std::cmp::Reverse;
use std::collections::BinaryHeap;

pub fn find_kth_largest(numbers: Vec<i32>, k: i32) -> i32 {
let k = k as usize;
let mut heap: BinaryHeap<_> = numbers[..k].iter().map(Reverse).collect();
for number in &numbers[k..] {
heap.push(Reverse(number));
heap.pop();
}
*heap.peek().unwrap().0
}

#[cfg(test)]
mod tests {
use test_case::test_case;

use crate::leetcode::kth_largest_element::find_kth_largest;

#[test_case(&[1, 2, 3, 4], 2, 3)]
#[test_case(&[1, 1, 3, 4, 5, 6], 5, 1)]
#[test_case(&[1, 2, 3], 1, 3)]
#[test_case(&[15, 5, 1, 3, 4, 5, 6, 9, 11], 2, 11)]
fn should_return_kth_largest_element(numbers: &[i32], k: i32, expected: i32) {
let result = find_kth_largest(numbers.to_vec(), k);
assert_eq!(result, expected);
}
}
1 change: 1 addition & 0 deletions src/leetcode/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,3 +19,4 @@ mod climb_stairs;
mod longest_subtsring;
mod largest_odd_number;
mod number_of_strings;
mod kth_largest_element;

0 comments on commit 4812419

Please sign in to comment.