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.
Here are few examples.
[1,3,5,6]
, 5 → 2
[1,3,5,6]
, 2 → 1
[1,3,5,6]
, 7 → 4
[1,3,5,6]
, 0 → 0
直接查找的方法
public class Solution {
public int searchInsert(int[] nums, int target)
{
int n=nums.length;
if(n==0)
return 0;
for(int i=0;i<n;i++)
{
if(nums[i]>=target)
return i;
}
return n;
}
}
二分法
二分法总是搞不清该返回 low 还是 high
若是真的要解释话. 最终 low == high, 这个时候, Mid = low = high. 假如 A[mid]>target, 那么插入位置就是 mid 处, 返回 low, OK. 假如 A[mid] < target, 那么 low = mid+1, 仍然返回 low
public class Solution {
public int searchInsert(int[] nums, int target)
{
int n=nums.length;
int i=0,j=n-1,k=0;
if(n==0)
return 0;
if(target>nums[n-1])
return n;
if(target<nums[0])
return 0;
while(i<=j)
{
k=(i+j)/2;
if(nums[k]<target)
i=k+1;
else if(nums[k]>target)
j=k-1;
else
return k;
}
return i;
}
}