折半查找+vector的应用(insert方法实际上是在下标之前插入新元素)
class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
int low=0,high=nums.size(),mid;
while(low<high)
{
mid=(low+high)/2;
if(nums[mid]==target)
return mid;
if(target<nums[mid])
high=mid;
else
low=mid+1;
}
if(target<nums[mid])
{
nums.insert(nums.begin()+mid,target);
return mid;
}
else if(mid<nums.size()-1)
{
nums.insert(nums.begin()+mid+1,target);
return mid+1;
}
else
{
nums.push_back(target);
return nums.size()-1;
}
}
};