Simple Java solution which is better than 69% in runtime.


  • 0
    H
    public class Solution {
        public int[] searchRange(int[] nums, int target) {
            int left_index = findTarget(nums, target, 0, nums.length - 1, true);
            int right_index = findTarget(nums, target, 0, nums.length - 1, false);
            return new int[] {left_index, right_index};
        }
        
        public int findTarget(int[] nums, int target, int start, int end, boolean isLeft) {
            if (start > end) {
                return -1;
            }
            int middle = (start + end) / 2;
            if (nums[middle] > target) {
                return findTarget(nums, target, start, middle - 1, isLeft);
            } else if (nums[middle] < target) {
                return findTarget(nums, target, middle + 1, end, isLeft);
            } else {
                int nextSearch = -1;
                if (isLeft) nextSearch = findTarget(nums, target, start, middle -1, isLeft);
                else nextSearch = findTarget(nums, target, middle + 1, end, isLeft);
                if (nextSearch != -1) return nextSearch;
                return middle;
            }
        }
    }

Log in to reply
 

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