35. Search Insert Position

思路:
直接二分查找即可。
代码:

class Solution {
public:
    int searchInsert(vector<int>& nums, int target) {
        int n = nums.size();
        int left=0,right=n-1;
        int  res=n;
        while(left<=right){
            int mid = (left+right)/2;
            if(target<=nums[mid]) {
                res=mid;
                right=mid-1;
            }
            else left=mid+1;
        }
        return res;
    }
};
posted @ 2021-04-25 21:53  Mrsdwang  阅读(31)  评论(0编辑  收藏  举报