https://leetcode-cn.com/problems/search-insert-position/description/

我的解决方案:二分

class Solution {
public static int searchInsert(int[] nums, int target) {
if(nums.length==0) return 0;
//使用二分查找
int low=0,high=nums.length-1,mid=(low+high)/2;
while(low<high) {
if(nums[mid]<target) low++;
else if(nums[mid]>target) high--;
else return mid;
mid = (low+high)/2;
}
if(nums[low]<target) return low+1;
else return low;
}
}

不好意思,我把二分法写错了,应该是这样的:

class Solution {
public static int searchInsert(int[] nums, int target) {
if(nums.length==0) return 0;
//使用二分查找
int low=0,high=nums.length-1,mid=0;
while(low<high) {
mid=(low+high)/2;
if(nums[mid]<target) low = mid+1;
else if(nums[mid]>target) high = mid-1;
else return mid;
}
if(nums[low]<target) return low+1;
else return low;
}
}

不过还有一种不使用二分法,而且也很高效的方案:

class Solution {
public int searchInsert(int[] nums, int target) {
int i, j=-1;
for(i=0; i<nums.length; i++){
if(nums[i] == target){
return i;
}
if(nums[i] < target){
j=i;
}
}

return j+1;

}
}