61. 搜索区间
给定一个包含 n 个整数的排序数组,找出给定目标值 target 的起始和结束位置。
如果目标值不在数组中,则返回[-1, -1]
样例
例1:
输入:
[]
9
输出:
[-1,-1]
例2:
输入:
[5, 7, 7, 8, 8, 10]
8
输出:
[3, 4]
挑战
时间复杂度 O(log n)
public class Solution {
/**
* @param A: an integer sorted array
* @param target: an integer to be inserted
* @return: a list of length 2, [index1, index2]
*/
public int[] searchRange(int[] A, int target) {
int left=0,right=A.length-1;
int center;
while (left<=right){
center=(left+right)/2;
// System.out.println(center+","+left+","+right);
if (A[center]>target){
right=center-1;
}else if (A[center]<target){
left=center+1;
}else {
left=center-1;
right=center+1;
while (left>=0){
if (A[left]==target)
left--;
else break;
}
while (right<A.length){
if (A[right]==target)
right++;
else break;
}
return new int[]{left+1,right-1};
}
}
return new int[]{-1,-1};
}
}