題目
給定一個包含 n 個整數(shù)的排序數(shù)組备禀,找出給定目標(biāo)值 target 的起始和結(jié)束位置黍特。
如果目標(biāo)值不在數(shù)組中显拜,則返回[-1, -1]
樣例
給出[5, 7, 7, 8, 8, 10]和目標(biāo)值target=8,返回[3, 4]
分析
二分搜索法逐工,先二分搜索左邊界凶朗,再二分搜索右邊界操骡,注意搜索時邊界的確定
搜索左邊界的時候九火,end = mid,保證最后留下的兩個數(shù)要么都等于target要么第一個小于
搜索右邊界的時候,start = mid册招,保證最后留下的兩個數(shù)岔激,要么一個大于,要么兩個都等于
代碼
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) {
// write your code here
if (A.length == 0) {
return new int[]{-1, -1};
}
int start, end, mid;
int[] bound = new int[2];
// search for left bound
start = 0;
end = A.length - 1;
while (start + 1 < end) {
mid = start + (end - start) / 2;
if (A[mid] == target) {
end = mid;
} else if (A[mid] < target) {
start = mid;
} else {
end = mid;
}
}
if (A[start] == target) {
bound[0] = start;
} else if (A[end] == target) {
bound[0] = end;
} else {
bound[0] = bound[1] = -1;
return bound;
}
// search for right bound
start = 0;
end = A.length - 1;
while (start + 1 < end) {
mid = start + (end - start) / 2;
if (A[mid] == target) {
start = mid;
} else if (A[mid] < target) {
start = mid;
} else {
end = mid;
}
}
if (A[end] == target) {
bound[1] = end;
} else if (A[start] == target) {
bound[1] = start;
} else {
bound[0] = bound[1] = -1;
return bound;
}
return bound;
}
}