返回指定值的下标
返回指定值的下标
题目
给定一个含有n个元素升序的整型数组nums和一个目标值target,写一个函数搜索nums中的target,如果目标值存在则返回目标值的下标,否则返回-1. 示例1:
输入:nums=[-1, 0, 3, 5, 7, 11], target=5
输出:3
解释:5出现在nums中并且下标为3
解法1:二分法
class Solution {
public int search(int[] nums, int target) {
int left=0;
int right=nums.length-1;
while(left<=right){ //在[left...right]里查找target
int mid=left+(right-left)/2; //为了防止left+right整型溢出,写成这样
if(nums[mid]==target){
return mid;
}else if(nums[mid]<target){ //下一轮搜索区间 [mid+1...right]
left=mid+1;
}else{ //此时nums[mid]>target,下一轮搜索区间 [left...mid-1]
right=mid-1;
}
}
return -1;
}
}
class Solution {
search(nums, target) {
let left = 0;
let right = nums.length - 1;
while (left <= right) {
let mid = Math.floor(left + (right - left) / 2);
if (nums[mid] === target) {
return mid;
} else if (nums[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1;
}
}
const solution = new Solution();
const nums = [1, 2, 3, 4, 5];
const target = 3;
const result = solution.search(nums, target);
console.log(result);
class Solution:
def search(self, nums, target):
left = 0
right = len(nums) - 1
while left <= right:
mid = left + (right - left) // 2
if nums[mid] == target:
return mid
elif nums[mid] < target:
left = mid + 1
else:
right = mid - 1
return -1
package main
import "fmt"
func search(nums []int, target int) int {
left := 0
right := len(nums) - 1
for left <= right {
mid := left + (right-left)/2
if nums[mid] == target {
return mid
} else if nums[mid] < target {
left = mid + 1
} else {
right = mid - 1
}
}
return -1
}
func main() {
nums := []int{1, 2, 3, 4, 5}
target := 3
result := search(nums, target)
fmt.Println(result)
}