clean and simple Java solution


  • 0
    H

    main idea is simple:make two binary search for target-0.5 and target+0.5。make sure to check if target is exist
    '''
    public int[] searchRange(int[] nums, int target) {
    int begin = binarySearch(nums,target-0.5);
    int end = binarySearch(nums, target+0.5)-1;
    if (begin<0||begin>nums.length-1||nums[begin]!=target){
    return new int[]{-1,-1};
    }

        return new int[]{begin,end};
    }
    
    private int binarySearch(int[] nums, double target) {
        int begin =0;
        int end=nums.length-1;
        while (begin<=end){
            int mid=(begin+end)/2;
            if (nums[mid]>target){
                end=mid-1;
            }else {
                begin=mid+1;
            }
        }
    
        return begin;
    }
    

    '''


Log in to reply
 

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