给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target ,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1
class Solution {
public int search(int[] nums, int target) {
if(target<nums[0] || target>nums[nums.length-1]){//默认有序
return -1;
}
int left = 0,right = nums.length-1;
while(left<=right){
int mid = left+((right-left)>>1);//防止溢出 >>右移运算符,相当于除以2
if(target==nums[mid]){
return mid;
}
else if(target<nums[mid]){
right = mid-1;
}
else if(target>nums[mid]){
left = mid+1;
}
}
return -1;
}
}