From 28a61d6000021666708b5fdd5b3a9c926c29fc85 Mon Sep 17 00:00:00 2001 From: jusexton Date: Thu, 19 Dec 2024 03:04:18 -0600 Subject: [PATCH] Added binary search solution. --- README.md | 1 + src/leetcode/binary_search.rs | 21 +++++++++++++++++++++ src/leetcode/mod.rs | 1 + 3 files changed, 23 insertions(+) create mode 100644 src/leetcode/binary_search.rs diff --git a/README.md b/README.md index b7145e3..c2371ff 100644 --- a/README.md +++ b/README.md @@ -163,6 +163,7 @@ programming challenges completed in other languages. - [Final Prices After Discounts](https://leetcode.com/problems/final-prices-with-a-special-discount-in-a-shop) - [Valid Palindrome](https://leetcode.com/problems/valid-palindrome) - [Roman to Integer](https://leetcode.com/problems/roman-to-integer) +- [Binary Search](https://leetcode.com/problems/binary-search) #### Medium diff --git a/src/leetcode/binary_search.rs b/src/leetcode/binary_search.rs new file mode 100644 index 0000000..a7db403 --- /dev/null +++ b/src/leetcode/binary_search.rs @@ -0,0 +1,21 @@ +pub fn search(numbers: Vec, target: i32) -> i32 { + match numbers.binary_search(&target) { + Ok(i) => i as i32, + Err(_) => -1, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn finds_element_index_when_it_exists() { + assert_eq!(4, search(vec![-1, 0, 3, 5, 9, 12], 9)) + } + + #[test] + fn negative_one_when_element_does_not_exist() { + assert_eq!(-1, search(vec![-1, 0, 3, 5, 9, 12], 20)) + } +} diff --git a/src/leetcode/mod.rs b/src/leetcode/mod.rs index 9407b41..6eb5576 100644 --- a/src/leetcode/mod.rs +++ b/src/leetcode/mod.rs @@ -151,3 +151,4 @@ mod xor_subarray; mod zero_or_one; mod zigzag_conversion; mod valid_sudoku; +mod binary_search;