LeetCode P35--Search Insertion Position

Title source: LeetCode
Link: https://leetcode-cn.com/problems/search-insert-position
Copyright is owned by LeetCode . For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.

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, return 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], 0
Output: 0

To find the insertion position, the most straightforward idea is to traverse the array and find thetargetThe subscripts of the elements with the same value are returned directly, or an element that is smaller than the target value but the next element is larger than the target value is found in the array, and the corresponding subscript is returned.

Another idea is to useBinary searchThe
following code is the binary search method code:

class Solution {
    
    
    public int searchInsert(int[] nums, int target) {
    
    
    	//初始化左、右指针
        int left = 0, right = nums.length - 1;
        while (left < right) {
    
    
            int mid = left + (right - left) / 2;
            //根据中间元素与target的大小比较来更新左右指针
            if (target > nums[mid]) {
    
    
                left = mid + 1;
            } else if (target < nums[mid]) {
    
    
                right = mid - 1;
            } else {
    
    
            //如果target==nums[mid],直接返回mid即可
                return mid;
            }
        }
        //如果没有相同元素,则target应该在left的左或者右
        return target > nums[left] ? left + 1 : left;
    }
}

Guess you like

Origin blog.csdn.net/weixin_44215175/article/details/107416760