Simple and Easy to Understand Binary Search Solution


  • 0
    M
    public int searchInsert(int[] nums, int target) {
            
            return searchInsertUtil(nums, 0, nums.length-1, target);
            
        }
        
        private int searchInsertUtil(int[] nums, int low, int high, int target) {
            
            if (low > high) return low;
            
            int mid = (low + high) / 2;
            
            if (target < nums[mid]) {
                
                // Recurse on the left half
                return searchInsertUtil(nums, low, mid - 1, target);
                
            } else if (target > nums[mid]) {
                
                // Recurse on the right half
                return searchInsertUtil(nums, mid + 1, high, target);
            }
            
            return mid;
        }
    

Log in to reply
 

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