最差情况遍历一遍,不过应该较容易想到二分法,只要注意边界就行。
class Solution {
public int searchInsert(int[] nums, int target) {
int length = nums.length;
if(length==0){
return 0;
}else if(length==1){
if(nums[0]>=target){
return 0;
}else{
return 1;
}
}
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 Math.max(left,right);
}
}