Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。
//手撕
class Solution {
public int searchInsert(int[] nums, int target) {
int length = nums.length;
//特殊情况判断减少循环
if(nums[0]>target){
return 0;
}
if(nums[length-1]<target){
return length;
}
int left = 0;
int right =length-1;
while(left<=right){
int mid = (left+right)/2;
if(nums[mid]==target){
return mid;
}else if(nums[mid]<target){
left=mid+1;
}else{
right=mid-1;
}
}
return left;
}
}
//改进部分
while(left<=right){
int mid = left + (right+left)/2;//防止数值溢出
...
}
点评:本题是基于二分查找的对目标值进行检索及寻找插入位置寻找,区别在于特殊情况的判断和插入位置的选择,考验点在二分查找双指针移动的知识点,通过画图模拟可得到插入位置为left下标
如何达到防止溢出:
数值溢出:数值溢出表示一个数值超出了该数值类型的表示范围结果会与想要得到的不同,一般较大的数值会出现该问题
防止溢出示例:假设现在数值超过10就会溢出,假设left=5 right=7两值相加5+7=12就会产生溢出,而5+(7-5)/2=6则不会溢出