当前位置:网站首页>Leetcode35. search the insertion position (simple, find the insertion position, different writing methods)

Leetcode35. search the insertion position (simple, find the insertion position, different writing methods)

2022-07-06 07:03:00 Heavy garbage

 Insert picture description here
 Insert picture description here
Two points : Library function

class Solution {
    
public:
    int searchInsert(vector<int>& nums, int target) {
    
        return lower_bound(nums.begin(), nums.end(), target) - nums.begin();
    }
};

Follow leetcode leetcode704. Two points search ( Find an element , Simple , Different ways of writing )
The intervals are different , there [l, r] yes [0, n] instead of [0, n - 1]
https://blog.csdn.net/zhangjiaji111/article/details/125601772

Right border n Is an out of bounds array , If you open it on the right , Will visit nums[n], Therefore, the right side can only be closed with the right : Left and right closed perhaps Left open right closed

1: Left open right closed

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

2: Left and right closed

class Solution {
    
public:
    int searchInsert(vector<int>& nums, int target) {
    

        int n = nums.size();
        int l = 0, r = n;
        while (l < r) {
     // When l==r Should exit the cycle when , So there was no ==
            int mid = l + (r - l) / 2;
            if (nums[mid] >= target) r = mid;
            else l = mid + 1;
        }
        return l; //return r Also on the 
    }
};

What to pay attention to :
 Insert picture description here

原网站

版权声明
本文为[Heavy garbage]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/187/202207060654495328.html