java solution


  • 0
    I

    public class Solution {
    public static void main(String[] args) {
    }

    public static int searchInsert(int[] nums, int target) {
        return binarySearch(nums, 0, nums.length, target);
    }
    
    public static int binarySearch(int[] nums, int begin, int end, int target) {
    
        int result = -1;
        int middle = (end + begin) >> 1;
    
        if(nums.length <= 0) {
            return 0;
        }
    
        while (begin < end) {
            if (begin < end && nums[middle] < target) {
                return binarySearch(nums, middle + 1, end, target);
            }
    
            if (begin < end && nums[middle] > target) {
                return binarySearch(nums, begin, middle, target);
            }
    
            if (nums[middle] == target) {
                return middle;
            }
    
        }
    
        if (begin == end) {
            if (nums[middle] == target || nums[middle] > target) {
                result = middle;
            }
    
            if (nums[middle] < target) {
                result = middle + 1;
            }
        }
    
        return result;
    }
    

    }


Log in to reply
 

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