LeetCode-35 search insertion position solution C++

Keywords: Algorithm leetcode

35. Search insertion positionhttps://leetcode-cn.com/problems/search-insert-position/

Simple difficulty 1103

Given a sort array and a target value, find the target value in the array and return its index. If the target value does not exist in the array, returns the position where it will be inserted in order.

Please use a time complexity of   O(log n)   Algorithm.

Example 1:

Input: num = [1,3,5,6], target = 5
 Output: 2

Example   2:

Input: num = [1,3,5,6], target = 2
 Output: 1

Example 3:

Input: num = [1,3,5,6], target = 7
 Output: 4

Example 4:

Input: num = [1,3,5,6], target = 0
 Output: 0

Example 5:

Input: num = [1], target = 0
 Output: 0

Tips:

  • 1 <= nums.length <= 104
  • -104 <= nums[i] <= 104
  • nums   Arranges the array in ascending order without repeating elements
  • -104 <= target <= 104

AC Code:

Train of thought analysis:

This question belongs to the same type as the previous binary search   So it can still be solved in two ways   One is anterior closure and posterior closure

One is front closed and back open   The insertion position is divided into four cases

  • The target value precedes all elements of the array
  • The target value is equal to an element in the array
  • The position where the target value is inserted into the array
  • The target value follows all elements of the array

 

 

First, the code of front closing and back closing is given

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

​

The front ones are all classic dichotomy   If this value is not found   Description exclude the case where the target value is equal to an element in the array, that is, the corresponding index cannot be found in the original array   The other three cases   It should return to the positions inserted in sequence

If one is at the front   When left=right = 0   If you still enter the while loop, right will change to - 1   Therefore, the subscript it returns should be (right+1), that is, the subscript 0

Second, if you insert a position in the array   My abstract thinking ability is not so good   I simulated it twice on paper

 

 

Word ugliness   Just spray

  three   If after all elements of the array

right will always keep its position   That is, the position of the last element   So if you want to insert   right+1

 

Front closing and rear opening

class Solution {
public:
    int searchInsert(vector<int>& nums, int target) {
        int n = nums.size();
        int left = 0;
        int right = n; // Define the target in the left closed right open interval, [left, right) target
        while (left < right) { // Because when left == right, the space in [left, right) is invalid
            int middle = left + ((right - left) >> 1);
            if (nums[middle] > target) {
                right = middle; // target is in the left interval, in [left, middle]
            } else if (nums[middle] < target) {
                left = middle + 1; // target is in the right interval, in [middle+1, right)
            } else { // nums[middle] == target
                return middle; // When the target value is found in the array, the subscript is returned directly
            }
        }
        // Deal with the following four situations respectively
        // Target value before all elements of array [0,0)
        // The target value is equal to an element in the array return middle
        // Insert the target value into the position [left, right] in the array and return right
        // If the target value is after all the elements of the array [left, right], return right
        return right;
    }
};

The first few lines of code are classic ideas of dichotomy   There's nothing to say   Just look at the last return   right

Four cases

First kind   The target element precedes all elements   Right will eventually become 0   So return right directly

Second   The target element is at an element position   Just return mid directly

Third   The target element is between two elements   Draw in the same way   Get return   mid

Fourth   Target element after all elements   It means right will not change   So just return right directly

brute-force attack

class Solution {
public:
    int searchInsert(vector<int>& nums, int target) {
        for (int i = 0; i < nums.size(); i++) {
        // Deal with the following three situations respectively
        // The target value precedes all elements of the array
        // The target value is equal to an element in the array
        // The position where the target value is inserted into the array
            if (nums[i] >= target) { // Once num[i] greater than or equal to target is found, I is the result we want
                return i;
            }
        }
        // The target value is after all elements of the array
        return nums.size(); // If target is the largest or num is empty, the length of num is returned
    }
};

Summary: Brush algorithm questions  

First, judge the type   What method is used

two   Read the questions well   Distinguish the situation   Treat separately or in combination according to each case

three   If abstract thinking doesn't work   Be good at drawing  

Posted by newzub on Sun, 03 Oct 2021 17:10:37 -0700