思路
暴力
public int[] searchRange(int[] nums, int target) {
int[] targetNums = {-1,-1};
//找到初始位置
for(int i=0;i<nums.length;i++){
if(nums[i]==target){
targetNums[0]=i;
break;
}
}
//如果没有找到 则返回-1
if(targetNums[0]==-1)
return targetNums;
//找到结束位置
for(int i=nums.length-1;i>=targetNums[0];i--){
if(nums[i]==target){
targetNums[1]=i;
break;
}
}
return targetNums;
}
二分
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;
}
}