Given a sorted array of integers, 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]
.
Have you met this question in a real interview?
思路 : 肯定是 binary search .最后再向两边扩展。
public class Solution {
public int[] searchRange(int[] A, int target) {
int[] ret = new int[2];
ret[0] = -1;
ret[1] = -1;
if(A.length < 1)
return ret;
int left = 0;
int right = A.length - 1;
boolean isFind = false;
while(left <= right){
int mid = (left + right) / 2;
if(A[mid] == target){
left = mid;
right = mid;
while(left >= 0 && A[left] == target)
left--;
while(right < A.length && A[right] == target)
right++;
ret[0] = left + 1;
ret[1] = right - 1;
return ret;
}else if(A[mid] < target)
left = mid + 1;
else
right =mid - 1;
}
return ret;
}
}