6ms Java Binary Search


  • 0
    public int[] searchRange(int[] nums, int target) {
            int start1=0, end1=nums.length-1;
            int start2=start1, end2=end1;
            int l=-1,r=-1;
            if(nums[0]==target) { l=0; }
            else{
                l=start1+(end1-start1)/2;
                while(start1<end1){
                    if(nums[l]<target) { start1=l+1; }
                    else if(l==0||(nums[l]==target&&nums[l-1]<target)) { break; }
                    else { end1=l; }
                    l=start1+(end1-start1)/2;
                }
                l=nums[l]==target?l:-1;
            }
            
            if(nums[end2]==target) { r=end2; }
            else{
                r=start2+(end2-start2)/2;
                while(start2<end2){
                    if(nums[r]>target) { end2=r; }
                    else if(r==nums.length-1||(nums[r]==target&&nums[r+1]>target)) { break; }
                    else { start2=r+1; }
                    r=start2+(end2-start2)/2;
                }
                r=nums[r]==target?r:-1;
            }
            int[] a=new int[2];
            a[0]=l;
            a[1]=r;
            return a;
        }
    

Log in to reply
 

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