利用二分查找法,但是速度是18%
二分查找中值的计算
常规算法: mid = (low + high)/ 2
试想一种极端的情况,low = 2147483640 , high = 10 , 则算出来的 mid 肯定是一个错误答案 ;
上面的表达式可以转化成: mid = ( (high - low + low + low) / 2 = low + ( high - low ) / 2
这样就可以避免 (low + high) 溢出的情况
同时 mid = low + ( high - low ) / 2 得出的结果更合期望的一致,向下取整
public int searchInsert(int[] nums, int target) {
if(nums.length == 0 || nums == null || target < nums[0]) return 0;
if(target > nums[nums.length-1]) return nums.length;
int start = 0,end = nums.length-1;
while(start < end){
int mid = start + (end - start)/2;
if(target > nums[mid]) {
start = mid + 1;
} else {
end = mid;
}
if(nums[mid] == target) return mid;
}
if(nums[start] < target) return start + 1;
else return start;
}
81%
public int searchInsert(int[] nums, int target) {
// if(nums.length == 0 || nums == null || target < nums[0]) return 0;
// if(target > nums[nums.length-1]) return nums.length;
int start = 0,end = nums.length-1;
while(start <= end){
int mid = (start + end)/2;
if(nums[mid] == target) return mid;
else if(nums[mid] > target) end = mid-1;
else start = mid+1;
}
return start;
}