详解二分查找算法 && leetcode35. 搜索插入位置

https://blog.csdn.net/weixin_39126199/article/details/118785065

 

https://leetcode.cn/problems/search-insert-position/

class Solution {
public:
    int searchInsert(vector<int>& nums, int target) {
        int l = 0;
        int r = nums.size() - 1;
        while(l <= r) {
            int mid = (l + r) / 2;
            if (nums[mid] ==  target) {
                return mid;
            }
            else if (nums[mid] <  target) {
                l = mid + 1;
            }
            else if (nums[mid] >  target) {
                r = mid - 1;
            }
        }
        
        return l;
        
        
    }
};

 

posted on 2022-08-14 22:29  TMatrix52  阅读(18)  评论(0编辑  收藏  举报

导航