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
问题说明:将一个数插入一个已排好的序列中,若数已存在,则返回其位置,不存在,返回其插入的位置。
int searchInsert(vector<int>& nums, int target)
{
auto e=find(nums.begin(),nums.end(),target);
if (e!=nums.end())
{
return (e-nums.begin());
}
else
{
int a=0;
int b=nums.size()-1;
while(a<=b)
{
int mid=(a+b)/2;
if (nums[mid]>=target)
{
b=mid-1;
}
else
{
a=mid+1;
}
}
return a;
}
}
AC