Java 1ms solution, recursive binary search, structure clear and simple, code style better


  • 3
    R
    public int[] searchRange(int[] nums, int target) {
        if(nums==null || nums.length==0){
            return new int[]{-1,-1};
        }
        else{
            return new int[]{
                getLeftBoundary(nums,0, nums.length-1,target),
                getRightBoundary(nums,0, nums.length-1,target)
            };
        }
    }
    private int getLeftBoundary(int[] nums, int start, int end, int target){
        if(start==end){
            if(nums[start]==target){
                return start;
            }
            return -1;
        }
        int mid = (start+end)/2;
        if(nums[mid]<target){
            return getLeftBoundary(nums, mid+1, end, target);
        }
        else{
            return getLeftBoundary(nums, start, mid, target);
        }
    }
    private int getRightBoundary(int[] nums, int start, int end, int target){
        if(start==end){
            if(nums[start]==target){
                return start;
            }
            return -1;
        }
    
        int mid = end-(end-start)/2;
        if(nums[mid]>target){
            return getRightBoundary(nums, start, mid-1, target);
        }
        else{
            return getRightBoundary(nums, mid, end, target);
        }
    }

Log in to reply
 

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