Java: recursive solution


  • 0
    H
    public int[] searchRange(int[] nums, int target) {
    	int left = low(nums, target, 0, nums.length - 1);
    	if(left == -1) return new int[] {-1, -1};
    	int right = high(nums, target, 0, nums.length - 1);
        return new int[] {left, right};
    }
    private static int low(int[] nums, int target, int left, int right)
    {
    	if(left == right) return (nums[left] == target) ? left : -1;
    	int mid = left + (right - left) / 2;
    	if(nums[mid] < target) return low(nums, target, mid + 1, right);
    	else return low(nums, target, left, mid);
    }
    private static int high(int[] nums, int target, int left, int right)
    {
    	if(left == right) return (nums[left] == target) ? left : -1;
    	int mid = right - (right - left) / 2;
    	if(nums[mid] > target) return high(nums, target, left, mid - 1);
    	else return high(nums, target, mid, right);
    }

Log in to reply
 

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