easy to understand java code with two binary search


  • 0
    B

    The code explains itself i think.

        public int[] searchRange(int[] nums, int target){
            if (nums.length == 0){
                return new int[]{-1, -1};
            }
            int leftBound = searchForLeftBound(nums, target);
            if (leftBound == -1){
                return new int[]{-1, -1};
            }
            int rightBound = searchForRightBound(nums, target, leftBound);
            return new int[]{leftBound, rightBound};
        }
        private int searchForLeftBound(int[] nums, int target){
            int left = 0;
            int right = nums.length - 1;
            while (left < right - 1){
                int mid = (left + right) / 2;
                if (nums[mid] == target){
                    right = mid;
                }else if (nums[mid] < target){
                    left = mid + 1;
                }else{
                    // nums[mid] > target
                    right = mid - 1;
                }
            }
            if (nums[left] == target){
                return left;
            }else if (nums[right] == target){
                return right;
            }else {
                return -1;
            }
        }
        private int searchForRightBound(int[] nums, int target, int leftBound){
            int left = leftBound;
            int right = nums.length - 1;
            while (left < right - 1){
                int mid = (left + right) / 2;
                if (nums[mid] == target){
                    left = mid;
                }else if (nums[mid] < target){
                    left = mid + 1;
                }else {
                    right = mid - 1;
                }
            }
            if (nums[right] == target){
                return right;
            }else if (nums[left] == target){
                return left;
            }else {
                return -1;
            }
        }
    

Log in to reply
 

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