Simple java solution( binary search)


  • 2
    public class Solution {
     public int searchInsert(int[] nums, int target) {
        if (nums == null || nums.length == 0) {
            return 0;
        }
    
        return position(nums, 0, nums.length - 1, target);
    
    }
    
    private int position(int[] nums, int start, int end, int target) {
        if(start > end){
            return start;
        }
    
        int mid = (start + end) / 2;
        if (nums[mid] == target) {
            return mid;
        } else if (nums[mid] > target) {
            return position(nums, start, mid - 1, target);
        } else {
            return position(nums, mid + 1, end, target);
        }
    
    }
    

    }


Log in to reply
 

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