diff --git a/src/solutions.rs b/src/solutions.rs index 0d15629..ec5dff3 100644 --- a/src/solutions.rs +++ b/src/solutions.rs @@ -11,5 +11,6 @@ mod s_46_permutations; mod s_543_diameter_of_binary_tree; mod s_567_permutation_in_string; mod s_572_subtree_of_another_tree; +mod s_704_binary_search; mod s_78_subset; mod s_79_word_search; diff --git a/src/solutions/s_704_binary_search.rs b/src/solutions/s_704_binary_search.rs new file mode 100644 index 0000000..f293c73 --- /dev/null +++ b/src/solutions/s_704_binary_search.rs @@ -0,0 +1,47 @@ +struct Solution {} + +impl Solution { + pub fn search(nums: Vec, target: i32) -> i32 { + let mut left_ptr = 0; + let mut right_ptr = nums.len() as i32 - 1; + while left_ptr <= right_ptr { + let mid_ptr = (right_ptr + left_ptr) / 2; + match target.cmp(&nums[mid_ptr as usize]) { + std::cmp::Ordering::Less => { + right_ptr = mid_ptr - 1; + } + std::cmp::Ordering::Equal => return mid_ptr as i32, + std::cmp::Ordering::Greater => { + left_ptr = mid_ptr + 1; + } + } + } + return -1; + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_exist() { + let input = vec![-1, 0, 3, 5, 9, 12]; + let res = Solution::search(input, 9); + assert_eq!(res, 4); + } + + #[test] + fn test_not_exist() { + let input = vec![-1, 0, 3, 5, 9, 12]; + let res = Solution::search(input, 2); + assert_eq!(res, -1); + } + + #[test] + fn test_single_element() { + let input = vec![1]; + let res = Solution::search(input, -1); + assert_eq!(res, -1); + } +}