-
Notifications
You must be signed in to change notification settings - Fork 0
/
s0704_binary_search.rs
50 lines (43 loc) · 1.25 KB
/
s0704_binary_search.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
struct Solution;
//leetcode submit region begin(Prohibit modification and deletion)
use std::cmp::Ordering::*;
impl Solution {
pub fn search(nums: Vec<i32>, target: i32) -> i32 {
let n = nums.len();
let mut left = 0;
let mut right = n - 1;
while left <= right {
let mid = ((right - left) >> 1) + left;
match nums[mid].cmp(&target) {
Equal => return mid as i32,
Less => {
if mid + 1 > n - 1 {
break;
}
left = mid + 1;
}
Greater => {
if mid < 1 {
break;
}
right = mid - 1;
}
}
}
-1
}
}
//leetcode submit region end(Prohibit modification and deletion)
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test() {
let nums1 = vec![-1, 0, 3, 5, 9, 12];
assert_eq!(Solution::search(nums1, 9), 4);
let nums2 = vec![-1, 0, 3, 5, 9, 12];
assert_eq!(Solution::search(nums2, 2), -1);
assert_eq!(Solution::search(vec![5], -5), -1);
assert_eq!(Solution::search(vec![2, 5], 2), 0);
}
}