描述
给定一个包含 n 个整数的排序数组,找出给定目标值 target 的起始和结束位置。如果目标值不在数组中,则返回[-1, -1]
样例
给出[5, 7, 7, 8, 8, 10]和目标值target=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) {
if (A == null || A.length == 0) {
return new int[] {-1, -1};
}
int startIndex = findStartIndex(A, target);
int endIndex = findEndIndex(A, target);
return new int[] {startIndex, endIndex};
}
private int findStartIndex(int[] A, int target) {
int start = 0, end = A.length - 1;
while (start + 1 < end) {
int mid = start + (end - start) / 2;
if (A[mid] == target) {
end = mid;
}
if (A[mid] < target) {
start = mid;
}
if (A[mid] > target) {
end = mid;
}
}
if (A[start] == target) {
return start;
}
if (A[end] == target) {
return end;
}
return -1;
}
private int findEndIndex(int[] A, int target) {
int start = 0, end = A.length - 1;
while (start + 1 < end) {
int mid = start + (end - start) / 2;
if (A[mid] == target) {
start = mid;
}
if (A[mid] < target) {
start = mid;
}
if (A[mid] > target) {
end = mid;
}
}
if (A[end] == target) {
return end;
}
if (A[start] == target) {
return start;
}
return -1;
}
}