/
three_way_fast.rs
55 lines (44 loc) · 1.35 KB
/
three_way_fast.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
pub struct Solution;
// ------------------------------------------------------ snip ------------------------------------------------------ //
use std::cmp::Ordering;
impl Solution {
pub fn search(nums: Vec<i32>, target: i32) -> i32 {
if nums.is_empty() {
-1
} else {
let mut start = 0;
let mut length = nums.len();
while length != 1 {
let half = length / 2;
let middle = start + half;
if nums[middle] <= target {
start = middle;
}
match nums[middle].cmp(&target) {
Ordering::Less => start = middle,
Ordering::Equal => return middle as _,
Ordering::Greater => {}
}
length -= half;
}
if nums[start] == target {
start as _
} else {
-1
}
}
}
}
// ------------------------------------------------------ snip ------------------------------------------------------ //
impl super::Solution for Solution {
fn search(nums: Vec<i32>, target: i32) -> i32 {
Self::search(nums, target)
}
}
#[cfg(test)]
mod tests {
#[test]
fn test_solution() {
super::super::tests::run::<super::Solution>();
}
}