From b1a05f3db71a43c51a32da42fa75b591f2c700d2 Mon Sep 17 00:00:00 2001 From: Gleb Koval Date: Sat, 11 Jun 2022 12:44:37 +0100 Subject: [PATCH] binary-search --- binary-search/sol.rs | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 binary-search/sol.rs diff --git a/binary-search/sol.rs b/binary-search/sol.rs new file mode 100644 index 0000000..385f520 --- /dev/null +++ b/binary-search/sol.rs @@ -0,0 +1,24 @@ +use std::cmp::Ordering; + +impl Solution { + pub fn search(mut nums: Vec, target: i32) -> i32 { + // nums.len() > 0 so this is safe to do + if *nums.first().unwrap_or(&-target) == target { + return 0; + } + let mut current = nums.as_slice(); + let mut idx = 0; + while current.len() > 1 { + let m = current.len() / 2; + match target.cmp(¤t[m]) { + Ordering::Equal => return (idx + m) as i32, + Ordering::Greater => { + current = current.split_at(m).1; + idx += m; + }, + Ordering::Less => current = current.split_at(m).0 + } + } + -1 + } +} \ No newline at end of file