您的位置:首页 > 其它

leetcode-35-Search Insert Position

2017-02-20 16:16 531 查看

问题

题目:[leetcode-35]

思路

二分查找,基础题。

但是,查找失败时的插入位置为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;
}

};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: