问题
思路
二分查找,基础题。
但是,查找失败时的插入位置为high+1或者low
代码
class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
return biSearch( nums, 0, nums.size()-1, target );
}
private:
int biSearch( const std::vector<int>& nums, int low, int high, int target ){
while(low <= high){
int mid = (low+high)/2;
if(target == nums[mid]) return mid;
else if( target < nums[mid] ) high = mid-1;
else low = mid+1;
}
return high+1;
}
};