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.
Example 1:
Input: [1,3,5,6], 5
Output: 2
Example 2:
Input: [1,3,5,6], 2
Output: 1
Example 3:
Input: [1,3,5,6], 7
Output: 4
Example 1:
Input: [1,3,5,6], 0
Output: 0
暴力解法可以Accepted 但是时间复杂度高
public int searchInsert(int[] nums, int target) {
int index=0;
for(int i= 0;i<nums.length;i++){
if(nums[i]==target){
index = i;
}
}
for(int i=1;i<nums.length;i++){
if(target>nums[i-1]&&target<nums[i]){
index = i;
}
}
for(int i=0;i<nums.length;i++){
if(target>nums[nums.length-1]){
index = nums.length;
}
}
return index;
}
最经典的二分查找方法
public int searchInsert(int[] A, int target) {
if(A == null || A.length == 0)
{
return 0;
}
int l = 0;
int r = A.length-1;
while(l<=r)
{
int mid = (l+r)/2;
if(A[mid]==target)
return mid;
if(A[mid]<target)
l = mid+1;
else
r = mid-1;
}
return l;
}
二分查找失败的时候,则l一定停在比目标大的index上,r一定停在比目标小的index