Java simple binary search, 0ms, o(n)


  • 0
    R
    public int searchInsert(int[] nums, int target) {
        int index= getSearchInsertIndex(nums,target,0, nums.length-1);
        if(index==nums.length-1){
            if(nums[index]<target){
                index++;
            }
        }
        return index;
    }
    private int getSearchInsertIndex(int[] nums, int target, int start, int end){
    
        if(start==end){
            return start;
        }
        int mid = (start+end)/2;
        if(nums[mid]<target){
          return  getSearchInsertIndex(nums,target,mid+1,end);
        }
        else{
          return  getSearchInsertIndex(nums,target,start,mid);
        }
    
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.