1ms Simple Java Solution


  • 0
    A
    public class Solution {
        public int[] searchRange(int[] nums, int target) {
            int idx1 = findIndex(nums, target, true);
            if (idx1 == -1) {
                return new int[]{-1, -1};
            } 
            int idx2 = findIndex(nums, target, false);
            return new int[]{idx1, idx2};
        }
        
        int findIndex(int[] nums, int target, boolean leftMost) {
            int low = 0, high = nums.length - 1;
            while (low < high) {
                int mid = (low + high) / 2;
                if (nums[mid] == target) {
                    if (leftMost == true) {
                        if (mid > 0 && nums[mid - 1] == target) high = mid;
                        else return mid;
                    } else {
                        if (mid <= nums.length - 2 && nums[mid + 1] == target) low = mid + 1;
                        else return mid;
                    }
                } else if (nums[mid] < target) low = mid + 1;
                else high = mid - 1;
                //System.out.println(low + " " + high + " " + mid);
            }
            return nums[low] == target ? low : -1;
        }
    }

Log in to reply
 

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