题目
给定一个n个元素有序(升序)整型数组nums和一个目标值target,写一个函数搜索nums中的target,如果目标值存在返回下标,否则返回-1。
题解
Java
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;
}
}