LeetCode:Search for a Range
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]
.
其实这道题很简单,就是二分查到一个位置,在前后查找与target这个Range。
public class Solution {
public int[] searchRange(int[] A, int target) {
int[] index = {-1,-1};
if(A == null|| A.length == 0)return index;
int left = 0;
int right = A.length - 1;
int mid = (left + right)/2;
while(left<=right)
{
if(A[mid] == target)
{
index = range(A,mid);
return index;
}
else if(A[mid]<target)
{
left = mid + 1;
}
else
{
right = mid - 1;
}
mid = (left + right)/2;
}
return index;
}
public int[] range(int[] A, int index)
{
int[] result = {index,index};
int left = index - 1;
int right = index + 1;
while(left>=0&&A[left] == A[index])
{
result[0] = left;
left = left - 1;
}
while(right<A.length&&A[right] == A[index])
{
result[1] = right;
right = right + 1;
}
return result;
}
}