一、题目要求

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.

Here are few examples.
[1,3,5,6], 5 → 2
[1,3,5,6], 2 → 1
[1,3,5,6], 7 → 4
[1,3,5,6], 0 → 0

二、题目分析

知识点:二分查找

三、代码

public class Solution {
    public int searchInsert(int[] nums, int target) {
        if(nums.length==0)
            return 0;
        int low=0;
        int high=nums.length-1;
        int mid;
        while(low<=high){
            mid=(low + high)/2;
            if(nums[mid]==target){
                return mid;
            }else if(target<nums[mid]){
                high=mid-1;
            }else{
                low= mid+1;  
            }
        }
        return low;
    }
}

  

 

相关文章:

  • 2021-09-29
  • 2021-11-08
  • 2022-03-06
  • 2021-11-27
  • 2021-10-18
  • 2021-07-28
猜你喜欢
  • 2022-01-03
  • 2021-07-12
  • 2021-08-12
  • 2021-08-09
  • 2021-07-12
  • 2021-09-27
  • 2021-09-07
  • 2021-09-21
相关资源
相似解决方案