Search Insert Position

Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.

You may assume no duplicates 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 1:

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

给定一个有序数组和一个数,判断是否有该数,有就返回位置,不存在则返回插入的位置。因为 是有序的数组插入,所以很容易想到二分法。

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)
                right=mid-1;
            else
                left=mid+1;
        }
        return left;
    }
}

代码解析:返回left是因为,到最后两个指针(left和right)都会先重合(这里考虑插入),重合后mid也和他们重合,如果该元素>target,right--,此时跳出,target应该存放在该元素的位置,也就是left;如果该元素<target,left++.target插入到该元素后面,因为left++了,所以也就是left位置。因为可以重合,所以一个元素的情况也是这样

原文地址:https://www.cnblogs.com/xiaolovewei/p/8064535.html