Straightforward Java Solution Using Binary Search


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

Log in to reply
 

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