二分法查找,数组中有target返回查找到的位置即为插入位置,若数组中没有target,跳出while 循环后返回low即为插入位置。
35. Search Insert Position
class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
int high=nums.size()-1;
int low=0;
int mid;
while (low<=high)
{
mid=(low+high)/2;
if (target<nums[mid])
high=mid-1;
else if (target>nums[mid])
low=mid+1;
else
return mid;
}
return low;
}
};