【LeetCode 35】搜索插入位置

题目链接

【题解】

还是那句话,想知道l或者r所在的数字的含义 就想想它最后一次执行的时候在干什么就行。

【代码】

class Solution {
public:
    int searchInsert(vector<int>& nums, int target) {
        int len = nums.size();
        int l = 0,r = len-1;
        while (l<=r){
            int mid = (l+r)/2;
            if (nums[mid]>target){
                r = mid-1;
            }else{
                //nums[mid]<=target
                l = mid+1;
            }
        }
        if (l-1>=0 && nums[l-1]==target){
            return l-1;
        }else return l;
    }
};
原文地址:https://www.cnblogs.com/AWCXV/p/11846844.html