搜索插入位置

思路

二分查找,注意如果target不在数组中时,需要判断一下下标

代码

class Solution {
    public int searchInsert(int[] nums, int target) {
        //二分查找
        int left = 0;
        int right = nums.length - 1;
        while(left < right){
            int mid = left + (right - left)/2;
            if(nums[mid] == target){
                return mid;
            }
            else if(nums[mid] > target){
                right = mid - 1;
            }
            else{
                left = mid + 1;
            }
         }
        if(target > nums[left]){
            return left + 1;
         }
        return left;
    }
}
posted @ 2020-07-17 22:58  zjy4fun  阅读(131)  评论(0编辑  收藏  举报