MCPcopy Create free account
hub / github.com/StudyRust/leetcode_rust / search

Function search

704-binary-search.rs:1–17  ·  view source on GitHub ↗
(nums: Vec<i32>, target: i32)

Source from the content-addressed store, hash-verified

1pub fn search(nums: Vec<i32>, target: i32) -> i32 {
2 let mut left = 0;
3 let mut right = nums.len() - 1;
4 while left <= right {
5 let mid = left + ( right - left ) / 2; // 游标是left作为起点,右侧总长除2,就是右边的中间。
6 if nums[mid] == target {
7 return mid as i32;
8 }
9 if nums[mid] > target {
10 right = mid - 1; // 如果在左区间,要左移1位,作为开始
11 }
12 if nums[mid] < target {
13 left = mid + 1; // 如果在右区间,要右移1位,作为开始
14 }
15 }
16 -1
17}
18
19fn main() {
20 let nums = vec![-1,0,3,5,9,12];

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected