题目描述:
Given a sorted array of integers,
find the starting and ending position of a given target value.Your algorithm's runtime complexity must be in the order of O(log n).
If the target is not found in the array, return [-1, -1].
For example,
Given [5, 7, 7, 8, 8, 10] and target value 8,
return [3, 4].
(给定一个排序过的整数数组(相等的数一定连在一起),找到起始和结束位置给定的目标值。
你的算法的时间复杂度必须为O(log n)。
如果目标没有在数组中被找到,返回[-1,-1]。
例如,
给[5,7,7,8,8,10]和目标值8,
返回[3,4]。)
public class Search_for_a_Range_二分查找 {
//返回的结果数组
public static int[] searchRange(int[] A, int target) {
int[] res = new int[2];
res[0] = -1;
res[1] = -1;
if(A==null || A.length==0)
{
return res;
}
int l=0;
int r=A.length-1;
int m=(l+r)/2;
//普通二分搜索找到数字
while(l<=r)
{
m=(l+r)/2;
if(A[m]==target)
{
res[0]=m;
res[1]=m;
break;
}
else if(A[m]>target)
{
r = m-1;
}
else
{
l = m+1;
}
}
//如果上面找不到该数字直接返回结果数组
if(A[m]!=target)
return res;
//搜索右面
int newL = m;
int newR = A.length-1;
while(newL<=newR)
{
int newM=(newL+newR)/2;
if(A[newM]==target)
{
newL = newM+1;
}
else
{
newR = newM-1;
}
}
res[1]=newR;
//搜索左面
newL = 0;
newR = m;
while(newL<=newR)
{
int newM=(newL+newR)/2;
if(A[newM]==target)
{
newR = newM-1;
}
else
{
newL = newM+1;
}
}
res[0]=newL;
return res;
}
public static void main(String[] args) {
int array[]={5,7,7,7,7,7};
int target=7;
System.out.println(Arrays.toString(searchRange(array, target)));
}
}