704. 二分查找 ★
力扣题目链接,给定一个 n
个元素有序的(升序)整型数组 nums
和一个目标值 target
,搜索 nums
中的 target
,如果存在返回下标,否则返回 -1
。n
将在 [1, 10000]
之间。
- 可以假设
nums
中的所有元素是不重复的。 n
将在[1, 10000]
之间。nums
的每个元素都将在[-9999, 9999]
之间。
示例 1:
输入: nums = [-1,0,3,5,9,12], target = 9
输出: 4
解释: 9 出现在 nums 中并且下标为 4
示例 2:
输入: nums = [-1,0,3,5,9,12], target = 2
输出: -1
解释: 2 不存在 nums 中因此返回 -1
本地练习
rust
pub struct Solution;
use std::cmp::Ordering;
impl Solution {
pub fn search(nums: Vec<i32>, target: i32) -> i32 {
}
}
fn main() {
let res = [(vec![-1, 0, 3, 5, 9, 12], 9), (vec![-1, 0, 3, 5, 9, 12], 2)]
.iter().map(|x| Solution::search(x.0.to_vec(), x.1)).collect::<Vec<_>>();
println!("{:?}: {:?}", vec![4, -1] == res, res);
}
Rust答案
- (版本一)左闭右开区间
rust
use std::cmp::Ordering;
impl Solution {
pub fn search(nums: Vec<i32>, target: i32) -> i32 {
let (mut left, mut right) = (0, nums.len());
while left < right {
let mid = (left + right) / 2;
match nums[mid].cmp(&target) {
Ordering::Less => left = mid + 1,
Ordering::Greater => right = mid,
Ordering::Equal => return mid as i32,
}
}
-1
}
}
- (版本二)左闭右闭区间
rust
use std::cmp::Ordering;
impl Solution {
pub fn search(nums: Vec<i32>, target: i32) -> i32 {
let (mut left, mut right) = (0, nums.len());
while left <= right {
let mid = (right + left) / 2;
match nums[mid].cmp(&target) {
Ordering::Less => left = mid + 1,
Ordering::Greater => right = mid - 1,
Ordering::Equal => return mid as i32,
}
}
-1
}
}