Letcode--35. Search insertion position

insert image description here

(1) Analyzing the method of violence to solve the problem:

 存在四种情况:
 ①目标值=数组内某元素,返回该元素的位置
 ②目标值≠数组内任一元素,返回插入位置
 ③目标值<数组内最小元素,返回0
 ④目标值>数组内最大元素,返回最后的位置(nums的长度)

violence law code

class Solution {
    
    
public:
    int searchInsert(vector<int>& nums, int target) {
    
    
        for (int i = 0; i < nums.size(); i++) {
    
    
            if (nums[i] >= target) {
    
     
                return i;
            }
        }
        return nums.size(); 
    }
};

Time complexity: O(n)
Space complexity: O(1)

(2) Analyzing the idea of ​​dichotomy to do the question:

Basic condition of binary search: ordered array

For example, in this array, use the binary method to find the position where the element is 5, and return its subscript.
insert image description here

Dichotomy Code (1)

The definition target is in a left-closed right-closed interval [left, right]

	分别处理如下四种情况
 ①目标值在数组所有元素之前  [0, -1]
 ②目标值等于数组中某一个元素  return middle;
 ③目标值插入数组中的位置 [left, right],return  right + 1
 ④目标值在数组所有元素之后的情况 [left, right], return right + 1
class Solution {
    
    
public:
    int searchInsert(vector<int>& nums, int target) {
    
    
    int n =nums.size();
    int left = 0;
    int right = n-1;
    while(left <= right){
    
    
        int middle = left+((right-left)/2);
             // 防止溢出 等同于(left + right)/2
        if (nums[middle] > target) {
    
    
              // target 在左区间,所以[left, middle - 1]
            right = middle - 1;
        }
        else if(nums[middle] < target){
    
     
               // target 在右区间,所以[middle + 1, right]
            left = middle + 1;
        }
        else{
    
     //num[middle] = target
            return middle;
        }
    }
    return right + 1; 
    }
};

Time complexity: O(logn)
Space complexity: O(1)

Dichotomy Code (2)

The definition target is in an interval [left, right) that is closed on the left and opened on the right.

分别处理如下四种情况
 ①目标值在数组所有元素之前 [0,0)
 ②目标值等于数组中某一个元素 return middle
 ③目标值插入数组中的位置 [left, right) ,return right 即可
 ④目标值在数组所有元素之后的情况 [left, right),return right 即可
class Solution {
    
    
public:
    int searchInsert(vector<int>& nums, int target) {
    
    
        int n = nums.size();
        int left = 0;
        int right = n;
         while (left < right) {
    
     
            int middle=left+((right-left)>>1);
             if (nums[middle] > target) {
    
    
                right = middle; 
            } else if (nums[middle] < target) {
    
    
                left = middle + 1; 
            } else {
    
     // nums[middle] == target
                return middle; 
            }
        }
        
        return right;

    }
};

Time complexity: O(logn)
Space complexity: O(1)

Method learning comes from here~~~

Guess you like

Origin blog.csdn.net/becomeyee/article/details/124552517