方法一:从小到大暴力搜索
class Solution {
public int searchInsert(int[] nums, int target) {
for(int i=0;i<nums.length;i++){
if(nums[i]>=target)return i;
}
return nums.length;
}
}
方法二:二分查找
二分查找有一些边界值容易出错,写完代码手动验证一下:
1、nums为空串
2、nums所有元素都比target小
3、nums所有元素都比target大
class Solution {
public int searchInsert(int[] nums, int target) {
if(nums.length==0)return 0;//空串
int left = 0;
int right = nums.length-1;
int mid = 0;
while(left<right){
mid = (left+right)/2;
if(nums[mid]==target)return mid;
else if(nums[mid]>target)right = mid-1;
else left = mid+1;
}
if(right<0)return 0;
if(nums[right]<target)return right+1;
else return right;
}
}