LeetCode第 35 题:搜索插入位置(C++)

35. 搜索插入位置 - 力扣(LeetCode)

简单题

class Solution {
public:
    //检索最后一个小于等于target的元素位置
    int bsearch(vector<int> &nums, int low, int high, int target){
        while(low <= high){
            int mid = (low+high)>>1;
            if(nums[mid] > target)  high = mid-1;
            else{
                if(mid == high || nums[mid+1] > target) return mid;
                low = mid+1;
            }  
        }
        return -1;
    }
    int searchInsert(vector<int>& nums, int target) {
        int res = bsearch(nums, 0, nums.size()-1, target);
        if(res == -1 || nums[res] != target)    return ++res;
        return res;
    }
};

猜你喜欢

转载自blog.csdn.net/qq_32523711/article/details/107802626