Java Solution using Binary Search


  • 0
    E
    public class Solution {
        public int[] searchRange(int[] nums, int target) {
            int index=findIndex(nums,target,0,nums.length-1);
            int res[]=new int[2];
            if(index==-1){
                res[0]=-1;
                res[1]=-1;
                return res;
            }
            int end=0,x=index;
            System.out.print(index);
            while(index+1<nums.length && nums[index]==nums[index+1]){
                index++;
            }
            end=index;
            index=x;
            while(index-1>=0 && nums[index]==nums[index-1]){
                index--;
            }
            res[0]=index;
            res[1]=end;
            return res;
        }
        public int findIndex(int arr[],int target,int start,int end){
            while(start<=end){
                int mid=start+(end-start)/2;
                if(arr[mid]==target){
                    return mid;
                }
                else if(arr[mid]<target){
                    start=mid+1;
                }
                else{
                    end=mid-1;
                }
            }
            return -1;
        }
    }
    

Log in to reply
 

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