My binary search solution:

class Solution {
    public int[] searchRange(int[] nums, int target) {
        if(nums==null || nums.length==0)
            return new int[]{-1,-1};
        
        int l =0, r = nums.length-1;
        while(l+1<r){
            int mid = (l+r)/2;
            if(nums[mid]>=target)
                r=mid;
            else
                l=mid;
        }
        
        int start = -1;
        if(nums[l]==target)
            start=l;
        else if(nums[r]==target)
            start=r;
        
        if(start!=-1){
            int end = start;
            for(int i=start+1;i<nums.length;i++){
                if(nums[i]==target)
                    end++;
            }
            return new int[]{start, end};
        }
        else
            return new int[]{-1,-1};
        
    }
}

 

posted on 2022-04-20 07:25  阳光明媚的菲越  阅读(14)  评论(0编辑  收藏  举报