LeetCode-35 搜索插入位置--查找

80 阅读1分钟

LeetCode-35 搜索插入位置--查找

在这里插入图片描述

然后就是标准的二分,当数组中没有时,最后插入的位置应该是left(最后一次循环已经left+1)

class Solution {
    int len;
    public int searchInsert(int[] nums, int target) {
        len = nums.length;
        int index = binarySearch(nums,target);
        return index;
    }

    public int binarySearch(int[] nums, int target){
        int l = 0,r = len - 1;
        int mid = 0;
        while(l <= r){
            mid = l + (r - l) / 2;
            if(nums[mid] > target) r = mid - 1;
            else if(nums[mid] < target) l = mid + 1;
            else return mid;
        }
        return l;
    }
}

时间复杂度O(logn) 空间复杂度O(1)