image.png

思路

暴力

  1. public int[] searchRange(int[] nums, int target) {
  2. int[] targetNums = {-1,-1};
  3. //找到初始位置
  4. for(int i=0;i<nums.length;i++){
  5. if(nums[i]==target){
  6. targetNums[0]=i;
  7. break;
  8. }
  9. }
  10. //如果没有找到 则返回-1
  11. if(targetNums[0]==-1)
  12. return targetNums;
  13. //找到结束位置
  14. for(int i=nums.length-1;i>=targetNums[0];i--){
  15. if(nums[i]==target){
  16. targetNums[1]=i;
  17. break;
  18. }
  19. }
  20. return targetNums;
  21. }

二分

class Solution {
    public int[] searchRange(int[] nums, int target) {
        int start = Solution.firstGreaterEqual(nums, target);
        if(start==nums.length||nums[start]!=target)
            return new int[]{-1,-1};
        return new int[]{start,Solution.firstGreaterEqual(nums, target+1)-1};
    }

    private static int firstGreaterEqual(int[] A,int target){
        int low = 0,high=A.length;
        while(low<high){
            int mid = low+((high-low)>>1);
            if(A[mid]<target)
                low=mid+1;
            else
                high=mid;
        }
        return low;
    }
}