Simple Java Solution


  • -1
    C

    public class Solution {
    public int[] searchRange(int[] nums, int target) {

        int index = bs(nums,target,0,nums.length-1);
        if(index == -1)return new int[]{-1,-1};
        
        int l=index,h=index;        
        while(l>=0 && nums[l] == target)l--;
        while(h<=(nums.length-1) && nums[h]==target)h++;
        
        return new int[]{l+1,h-1};
    

    }

    public int bs(int[]nums, int target, int low, int high)
    {   
        if(low>high)return -1;
        int mid = (low+high)/2;
        if(nums[mid] == target)return mid;
        if(nums[mid] > target)return bs(nums,target,low,mid-1);
        else return bs(nums,target,mid+1,high);
    }
    

    }


  • 0
    L

    due to " while(l>=0 && nums[l] == target)l--; while(h<=(nums.length-1) && nums[h]==target)h++; " these 2 lines, your algorithm is O(n). requirement is O(logn)


Log in to reply
 

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