34. Search for a Range
原创
©著作权归作者所有:来自51CTO博客作者wx62ea2466cca9a的原创作品,请联系作者获取转载授权,否则将追究法律责任
Given an array of integers sorted in ascending order, 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].
public class Solution {
public int[] searchRange(int[] A, int target) {
int left = 0;
int right = A.length - 1;
int[] result = { -1, -1 };
while (left <= right) {
int mid = (left + right) / 2;
if (A[mid] > target) {
right = mid - 1;
} else if (A[mid] < target) {
left = mid + 1;
} else {
result[0] = mid;
result[1] = mid;
int i = mid - 1;
while (i >= 0 && A[i] == target) {
result[0] = i;
--i;
}
i = mid + 1;
while (i < A.length && A[i] == target) {
result[1] = i;
++i;
}
break;
}
}
return result;
}
}