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 ofO(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]
.
题意:返回数组nums中等于target的元素的开始结束坐标,未找到返回[-1,-1],要求O(LogN)的时间复杂度。
解析:找到nums中石头有这个元素很简单,因为是sorted的array,折半查找可以找到其中一个元素等于target ,其他的元素也分布在两边。可以使用two pointers,一个向前一个向后,分别找到第一个不等于target的元素。
代码实现:
public class Solution
{
public int[] SearchRange(int[] nums, int target)
{
if (nums.Length == 0)
return new int[] { -1, -1 };
int begin = 0;
int end = nums.Length - 1;
int mid = (end + begin) / 2;
while (begin < end)
{
if (nums[mid] < target)
{
begin = mid + 1;
mid = (begin + end) / 2;
}
else if (nums[mid] > target)
{
end = mid - 1;
mid = (begin + end) / 2;
}
else
break;
}
if (nums[mid] != target)
return new int[] { -1, -1 };
for (begin = mid; begin >= 0; begin--)
{
if (nums[begin] != target)
break;
}
for (end = mid; end < nums.Length; end++)
{
if (nums[end] != target)
break;
}
return new int[] { begin + 1, end - 1 };
}
}