binary-search

This commit is contained in:
Gleb Koval 2022-06-11 12:44:37 +01:00
parent ca606b7be8
commit b1a05f3db7
Signed by: cyclane
GPG Key ID: 15E168A8B332382C
1 changed files with 24 additions and 0 deletions

24
binary-search/sol.rs Normal file
View File

@ -0,0 +1,24 @@
use std::cmp::Ordering;
impl Solution {
pub fn search(mut nums: Vec<i32>, 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(&current[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
}
}