Skip to content

Commit

Permalink
add 704. Binary Search
Browse files Browse the repository at this point in the history
  • Loading branch information
stada526 committed May 29, 2024
1 parent 5a11b45 commit dc73a0c
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/solutions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
47 changes: 47 additions & 0 deletions src/solutions/s_704_binary_search.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
struct Solution {}

impl Solution {
pub fn search(nums: Vec<i32>, 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);
}
}

0 comments on commit dc73a0c

Please sign in to comment.