给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target ,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。
输入: nums = [-1,0,3,5,9,12], target = 9
输出: 4
解释: 9 出现在 nums 中并且下标为 4
输入: nums = [-1,0,3,5,9,12], target = 2
输出: -1
解释: 2 不存在 nums 中因此返回 -1
let search = (nums, target) => {
if (nums === null || nums.length === 0)
return -1;
let l = 0, h = nums.length - 1;
while (l <= h) {
let m = l + Math.floor((h - l) / 2);
if (nums[m] === target)
return m;
else if (nums[m] < target)
l = m + 1;
else
h = m - 1;
}
return -1;
};
console.log(search([-1,0,3,5,9,12], 9))
console.log(search([-1,0,3,5,9,12], 2))
func search(nums []int, target int) int {
if nums == nil || len(nums) == 0 {
return -1
}
l, h := 0, len(nums) - 1
for l <= h {
m := l + (h - l) / 2
if nums[m] == target {
return m
} else if nums[m] < target {
l = m + 1
} else {
h = m - 1
}
}
return -1
}
class Solution {
public int search(int[] nums, int target) {
if (nums == null || nums.length == 0) return -1;
int l = 0, h = nums.length - 1;
while (l <= h) {
int m = l + (h - l) / 2;
if (nums[m] == target) return m;
else if (nums[m] < target) l = m + 1;
else h = m - 1;
}
return -1;
}
}