Insert position

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, return the position where it will be inserted in order.

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

Example 1:
Analysis:
We can perform binary search in a circular manner.
Insert picture description here
E.g
Insert picture description here

Code:

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

        while(index==-1){
    
    
            int mid=(begin+end)/2;
            if(target==nums[mid]){
    
    
                index= mid;
            }
          else  if(target<nums[mid]){
    
    
           if(mid==0 || target>nums[mid-1]){
    
    
                 index= mid;       
            }
             end=mid-1;
          }
          else  if(target>nums[mid] ){
    
    
           if(mid==end || target<nums[mid+1]){
    
    
                index= mid+1;
            }
            begin=mid+1;
        }   
    }
    return index;
    }
}

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.

Guess you like

Origin blog.csdn.net/weixin_42120561/article/details/114412389