704. Binary Search
https://leetcode.com/problems/binary-search/
Python
class Solution:
def search(self, nums: List[int], target: int) -> int:
l, r = 0, len(nums)-1
while l <= r:
cur = (l+r) // 2
if nums[cur] == target:
return cur
if nums[cur] < target:
l = cur + 1
else:
r = cur - 1
return -1
Go
func search(nums []int, target int) int {
left, right := 0, len(nums)-1
for left <= right {
pivot := (left+right) / 2
if (nums[pivot] == target) {
return pivot
} else if (nums[pivot] < target) {
left = pivot + 1
} else {
right = pivot - 1
}
}
return -1
}
Rust
impl Solution {
pub fn search(nums: Vec<i32>, target: i32) -> i32 {
let mut left:usize = 0;
let mut right:usize = nums.len() - 1;
while left < right {
let pivot:usize = (left+right) / 2;
// println!("pivot: {0}", pivot);
if nums[pivot] == target {
return pivot as i32;
} else if nums[pivot] < target {
left = pivot + 1;
} else {
right = pivot;
}
}
if nums[left] == target { left as i32 } else { -1 }
}
}