My java solution using binary search


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

    }


Log in to reply
 

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