Java Solution


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

Log in to reply
 

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