Java Esay solution. Just regular binary search


  • 0
    R

    Do the binary search as usual. When finding target number, just loop through array.

    public class Solution {
        public int[] searchRange(int[] nums, int target) {
            int start =0,end = nums.length-1;
            int[] res = {-1,-1};
            int mid =-1;
            while(start<=end){
                mid = start + (end-start)/2;
                if(nums[mid]==target){
                  break;
                }else if(nums[mid]>target){
                    end = mid-1;
                }else{
                    start = mid+1;
                }
            }
            if(nums[mid]== target){//to avoid cases when target not found
                int a=mid,b=mid;
                while(a>0){
                    if(nums[a-1]==target){a--;}else{break;}
                }
                while(b<nums.length-1){
                    if(nums[b+1]==target){b++;}else{break;}
                }
                res[0] = a;
                res[1] = b; 
            }
            return res;
        }
    }
    

Log in to reply
 

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