My intuitive Java solution with 2 searches, returning the integer bounds rather than the bound array


  • 0
    M
    public class Solution {
        public int[] searchRange(int[] nums, int target) {
            int[] result = new int[] {-1, -1};
            if (nums ==null || nums.length==0) return result;
            if (nums.length==1) {
                return (nums[0]==target) ? new int[2] : result;
            }
            result[0] = searchLeftBound(nums, target, 0, nums.length-1);
            result[1] = searchRightBound(nums, target, 0, nums.length-1);
            return result;
        }
        
        public int searchLeftBound(int[] nums, int target, int left, int right){
            //exit case, left+1 = right
            if (right == left +1){
                if(nums[left] == target) {
                    return left;
                }else if (nums[right] == target){
                    return right;
                }
                return -1;
            }
            //find mid
            int mid = (right + left)/2;
            if (nums[mid] < target) return searchLeftBound(nums, target, mid, right);
            return searchLeftBound(nums, target, left, mid);
        }
        
        public int searchRightBound(int[] nums, int target, int left, int right){
            //exit case, left+1 = right
            if (right == left +1){
                if(nums[right] == target) {
                    return right;
                }else if (nums[left] == target){
                    return left;
                }
                return -1;
            }
            //find mid
            int mid = (right + left)/2;
            if (nums[mid] > target) return searchRightBound(nums, target, left, mid);
            return searchRightBound(nums, target, mid, right);
        }
    }
    

Log in to reply
 

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