Search Insert Position

Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.

You may assume no duplicates in the array.

Here are few examples. [1,3,5,6], 5 → 2 [1,3,5,6], 2 → 1 [1,3,5,6], 7 → 4 [1,3,5,6], 0 → 0

lower_bound的写法

这道题目中若将mid = lb + (ub - lb)/2就不对,分析一下[1, 3, 5] 4

初始 lb = -1, ub = 3 求出的mid = 2;就出错了
class Solution {
public:
    int searchInsert(vector<int>& nums, int target) {
        int lb = -1;
        int ub = nums.size();

        while(ub - lb > 1){
            int mid = (ub + lb)/2;

            if(nums[mid] < target)
                lb = mid;
            else
                ub = mid;
        }

        return ub;
    }
};

results matching ""

    No results matching ""