LeetCode Algorithm C++ Brush Questions-searchInsert

Today's question

Given a sorted 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.

You can assume that there are no duplicate elements in the array.

Example 1:

Input: [1,3,5,6], 5
Output: 2

Example 2:

Input: [1,3,5,6], 2
Output: 1

Example 3:

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

Example 4:

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

Problem-solving ideas:

Given an array that has been sorted from small to large, it is required to find the position to insert the target element in the array.
This question is a variant of the classic binary search, which finds the last element smaller than target in an ordered array.

Sample code:

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

Today's question is similar to the previous LeetCode algorithm c++ brush question-searchFirstLastEqualElement . It's already been done, so it's easy.

Guess you like

Origin blog.csdn.net/u010196944/article/details/127639757