Java Recursive solution using Binary Search


  • 0
    public class Solution {
        public int[] searchRange(int[] nums, int target) {
            int range[]= new int[2];
            Arrays.fill(range,-1);
            if(nums.length==0){
                return range;
            }
            findRange(0,nums.length-1,nums,range,target);
            return range;
        }
        public static void findRange(int low, int high, int[] nums, int[] range, int target){
            if(low>high){
                return;
            }
            int mid= (high+low)/2;
            if(nums[mid]==target){
                range[0]= range[0]!=-1 ? Math.min(range[0],mid):mid;
                range[1]= Math.max(range[1], mid);
                findRange(mid+1, high, nums, range, target);
                findRange(low, mid-1, nums, range, target);
            }
            else if(nums[mid]<target){
                findRange(mid+1, high, nums, range, target);
            } 
            else{
                   findRange(low, mid-1, nums, range, target);
            }
        }
    }

Log in to reply
 

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