【Likou Daily Question 04】Arrays--Search Insertion Position

Today's topic uses the principle of binary search. Unfortunately, I didn't make it again, but I am also very happy to find my own shortcomings~

1. Topic

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.

Example 1:

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

Example 2:

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

Example 3:

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

Two, thinking analysis

Since I can't understand the official answer, I found another method that is easier to understand.

I believe everyone has learned binary search in C language, but they have forgotten it.

This solution first defines three variables: left , right , mid .

And assign the value left = 0; right = nums.length-1;

The definition of mid will be closed first, and I will talk about it later.

After this is done, as long as you understand the concept, the rest is very simple.

There are three cases, nums[mid] == target, nums[mid] <= target and nums[mid] >mid;

In the first case, it proves that we have found it, just return mid directly, because at this time mid happens to be the subscript of the inserted element

In the second case, it means that the value given by mid is too small, we let left ++, and explain later

The third type is not much different from the second type, the mid is too large, let's let the right -- first.

After completion, we loop this process again, and at the same time, define the variable mid = ( right + left ) /2 in the loop;

And you're done.

3. Complete code

class Solution {
    public int searchInsert(int[] nums, int target) {
        int left = 0;
        int right = nums.length-1;
        

        while(left<=right){

        int mid = (left+right)/2;

        if(nums[mid]==target) {
            return mid;
        }

        else if(nums[mid]<=target){
            left  = mid+1;
         }
            
        else {
             right = mid-1;
         }
        }


    return left;
    }
}

The above is the whole content of this blog. If there are any deficiencies, please point them out. I look forward to making progress with you!

Guess you like

Origin blog.csdn.net/C_Small_Cai/article/details/132661489