虽然@Arturo Menchaca 的答案是正确的,但我认为递归解决方案可能有点难以理解。因此,对于那些喜欢迭代方法的人...
public int[] FindRange(int[] arr, int value)
{
int[] upperLowerBounds = new int[2];
int startIndex = 0;
int endIndex = arr.Length - 1;
while (startIndex < endIndex)
{
int midIndex = (startIndex + endIndex) / 2;
if (value <= arr[midIndex])
{
endIndex = midIndex;
}
else
{
startIndex = midIndex + 1;
}
}
// saving startIndex in the result array that will be returned...
upperLowerBounds[0] = startIndex;
endIndex = arr.Length - 1;
while (startIndex < endIndex)
{
int midIndex = (startIndex + endIndex) / 2 + 1;
if (value < arr[midIndex])
{
endIndex = midIndex -1;
}
else
{
startIndex = midIndex;
}
}
upperLowerBounds[1] = endIndex;
return upperLowerBounds;
}
和单元测试..
[TestCase(new int[] { -4, -3, -3, -3, -3, -3, -3, -3, -3, -3, -1, 1, 6, 8, 10, 10, 10, 10, 10, 10, 25 }, -3, 1, 9)] // search element = -3
[TestCase(new int[] { -4, -3, -1, 1, 6, 8, 10, 10, 10, 10, 10, 10, 25 }, 6, 4, 4)] // search element = 6
[TestCase(new int[] { -4, -3, -1, 1, 6, 8, 10, 10, 10, 10, 10, 10, 25 }, 10, 6, 11)] // search element = 10
[TestCase(new int[] { -4, -3, -3, -3, -3, -3, -3, -3, -3, -3, -1, -1, -1, -1, -1, -1, -1, -1, 1, 6, 8, 10, 10, 10, 10, 10, 10, 25 }, -1, 10, 17)] // search element = -1
[TestCase(new int[] { 1, 1, 1, 3, 3, 9, 10 }, 3, 3, 4)] // search element = 3
[TestCase(new int[] { 1, 1, 1, 3, 3, 9, 10 }, 1, 0, 2)] // search element = 1
public void FindRangeTest(int[] arr, int value, int expectedStartIndex, int expectedEndIndex)
{
int[] range = runner.FindRange(arr, value);
// Assert.
Assert.AreEqual(expectedStartIndex, range[0]);
Assert.AreEqual(expectedEndIndex, range[1]);
}
我用过 C# 和 nunit 3.10