search-insert-position
This commit is contained in:
parent
2408262b66
commit
807ce27309
|
@ -0,0 +1,24 @@
|
||||||
|
use std::cmp::Ordering;
|
||||||
|
|
||||||
|
impl Solution {
|
||||||
|
pub fn search_insert(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(¤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
|
||||||
|
}
|
||||||
|
}
|
||||||
|
(idx + if current[0] < target { 1 } else { 0 }) as i32
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in New Issue