描述
给出一个有序数组,请在数组中找出目标值的起始位置和结束位置
你的算法的时间复杂度应该在O(log n)之内
如果数组中不存在目标,返回[-1, -1].
例如:
给出的数组是[50, 70, 70, 80, 80, 100],目标值是80,
返回[3, 4].
示例1
输入:
[50, 70, 70, 80, 80, 100],80
返回值:
[3,4]
public class Solution {
public int[] searchRange(int[] A, int target) {
int[] a = {-1,-1};
if(A==null||a.length<2)
return a;
int low, high, mid;
low = 0;
high = A.length - 1;
while (low <= high) {
mid = (high + low) / 2;
if (target == A[mid]) {
int temp = mid;
//向前搜索
while (mid - 1 >=0 && A[mid - 1] == target) {
mid--;
}
a[0] = mid;
mid = temp;
//向后搜索
while (mid + 1 < A.length && A[mid + 1] == target) {
mid++;
}
a[1] = mid;
break;
} else if (target < A[mid]) {
high = mid - 1;
} else {
low = mid + 1;
}
}
return a;
}
}