使用二分找到target后,在两侧分别使用二分找到起点和终点。
class Solution {
public int[] searchRange(int[] nums, int target) {
int lo = 0 ;
int hi = nums.length-1;
int pos = -1;
while(lo<=hi)
{
int mid = lo+(hi-lo)/2;
if(nums[mid]==target)
{
pos=mid;
break;
}
else if(nums[mid]<target)
{
lo=mid+1;
}
else
hi=mid-1;
}
int[] result = new int[2];
if(pos==-1)
{
result[0]=-1;
result[1]=-1;
return result;
}
lo = 0;
hi=pos;
while(lo<=hi)
{
int mid = lo+(hi-lo)/2;
if(nums[mid]<target)
{
lo=mid+1;
}
else
hi=mid-1;
}
int start =lo;
lo = pos;
hi=nums.length-1;
while(lo<=hi)
{
int mid = lo+(hi-lo)/2;
if(nums[mid]>target)
{
hi=mid-1;
}
else
lo=mid+1;
}
int end =lo-1;
result[0]=start;
result[1]=end;
return result;
}
}
网友评论