Simple


  • 0
    B

    The idea here is to find any any index of the target in the array using binary search. Then simply expand from that point to give the range.

    public class Solution {
    
    public int[] searchRange(int[] nums, int target) {
        return expandFromIndex(nums, getIndex(nums, target), target);
    
    }
    public int getIndex(int[] nums, int target) {
        int left = 0;
        int right = nums.length - 1;
        while(left <= right) {
            int mid = left + (right - left)/2;
            if(nums[mid] == target) return mid;
            else if(nums[mid] > target) right = mid - 1;
            else left = mid + 1;
        }
        return -1;
    }
    
    
    public int[] expandFromIndex(int[] nums, int index, int target) {
        int start = index;
        int end = index;
        if(index == -1) return new int[]{-1, -1};
        while(start >= 0 && nums[start] == target) start--;
        while(end < nums.length && nums[end] == target) end++;
        
        return new int[]{start + 1, end - 1};
        
    }
    

    }
    '''


Log in to reply
 

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