给定一个 n
个元素有序的(升序)整型数组 nums
和一个目标值 target
,写一个函数搜索 nums
中的 target
,如果目标值存在返回下标,否则返回 -1
。
示例 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
提示:
- 你可以假设
nums
中的所有元素是不重复的。 n
将在[1, 10000]
之间。nums
的每个元素都将在[-9999, 9999]
之间。
class Solution:
def search(self, nums: List[int], target: int) -> int:
left, right = 0, len(nums) - 1
while left < right:
mid = (left + right) >> 1
if nums[mid] >= target:
right = mid
else:
left = mid + 1
return left if nums[left] == target else -1
class Solution {
public int search(int[] nums, int target) {
int left = 0, right = nums.length - 1;
while (left < right) {
int mid = (left + right) >> 1;
if (nums[mid] >= target) {
right = mid;
} else {
left = mid + 1;
}
}
return nums[left] == target ? left : -1;
}
}
class Solution {
public:
int search(vector<int>& nums, int target) {
int left = 0, right = nums.size() - 1;
while (left < right) {
int mid = left + right >> 1;
if (nums[mid] >= target)
right = mid;
else
left = mid + 1;
}
return nums[left] == target ? left : -1;
}
};
func search(nums []int, target int) int {
left, right := 0, len(nums)-1
for left < right {
mid := (left + right) >> 1
if nums[mid] >= target {
right = mid
} else {
left = mid + 1
}
}
if nums[left] == target {
return left
}
return -1
}
/**
* @param {number[]} nums
* @param {number} target
* @return {number}
*/
var search = function (nums, target) {
let left = 0;
let right = nums.length - 1;
while (left < right) {
const mid = (left + right) >> 1;
if (nums[mid] >= target) {
right = mid;
} else {
left = mid + 1;
}
}
return nums[left] == target ? left : -1;
};
循环:
use std::cmp::Ordering;
impl Solution {
pub fn search(nums: Vec<i32>, target: i32) -> i32 {
let mut l = 0;
let mut r = nums.len();
while l < r {
let mid = l + r >> 1;
match nums[mid].cmp(&target) {
Ordering::Less => l = mid + 1,
Ordering::Greater => r = mid,
Ordering::Equal => return mid as i32,
}
}
-1
}
}
递归:
use std::cmp::Ordering;
impl Solution {
fn binary_search(nums: Vec<i32>, target: i32, l: usize, r: usize) -> i32 {
if l == r {
return if nums[l] == target { l as i32 } else { -1 };
}
let mid = l + r >> 1;
match nums[mid].cmp(&target) {
Ordering::Less => Self::binary_search(nums, target, mid + 1, r),
Ordering::Greater => Self::binary_search(nums, target, l, mid),
Ordering::Equal => mid as i32,
}
}
pub fn search(nums: Vec<i32>, target: i32) -> i32 {
let r = nums.len() - 1;
Self::binary_search(nums, target, 0, r)
}
}