My Java Solution with binary search 272 ms


  • 0
    K
    public int searchInsert(int[] nums, int target) {
             if(target>nums[nums.length-1]){
               return nums.length;
            }
          return modifiedBinarySearch(nums, target, 0, nums.length-1);
        }
    
    public static int modifiedBinarySearch(int nums[], int target, int start, int end){
        int mid = -1;
       while(start<=end){
         mid = start + (end-start) /2;
    
           if(target < nums[mid]){
                end = mid-1;
           }
           else if(target == nums[mid]){
               return mid;
           }
           else{
               start = mid+1;
           }
       }
        return (target> nums[mid])? mid+1 : mid;
    }

Log in to reply
 

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