leetcode-35-Search Insert Position

来源:互联网 发布:淘宝魅力惠里有假货吗 编辑:程序博客网 时间:2024/05/03 00:22

问题

题目:[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;    }};
0 0