Given a sorted array 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.
You may assume no duplicates in the array.
Here are few examples.
[1,3,5,6], 5 → 2
[1,3,5,6], 2 → 1
[1,3,5,6], 7 → 4
[1,3,5,6], 0 → 0
思路:第一反应就是“对半折”,
while(end-start>1),如果mid匹配了,直接返回mid的坐标
若从循环中出来了,再判断。第一次提交的时候就是判断出问题了,没考虑target>nums[end]情况
public int searchInsert(int[] nums, int target) {
int len = nums.length;
if(len==0)
return 0;
int start = 0;int end = len-1;
while(end-start>1){
int mid = (start+end)/2;
if(nums[mid]>target){
end = mid;
}else if(nums[mid]<target){
start = mid;
}else{
return mid;
}
}
if(nums[start]==target)
return start;
if(nums[end]==target)
return end;
if(nums[start]>target)
return start;
else if(nums[end]<target)
return end+1;
else
return start+1;
}
循环中逻辑还是很好的优化,当mid不匹配的时候,end=mid-1 而不是mid 然后start=mid+1
这样循环判断的条件就是while(start>=end),退出循环的时候还不用多余的判断
public int searchInsert(int[] nums, int target) {
int start = 0;int end = nums.length-1;
while(start<=end){
// int mid = (start+end)/2;
int mid = start+(end-start)/2;
if(nums[mid]==target)
return mid;
else if(nums[mid]>target)
end = mid-1;
else
start = mid+1;
}
return start;
}
然后还会存在一个小小bug
int mid = (start+end)/2;
当start和end很大的时候会溢出,所以可以
int mid =start+(end-start)/2;