Approach: Use binary search
public int[] SearchRange(int[] nums, int target)
{
if (nums == null || nums.Length <= 0)
{
return new int[] { -1, -1 };
}
if (nums.Length == 1)
{
return nums[0] == target ? new int[] { 0, 0 } : new int[] { -1, -1 };
}
int first = this.GetFirstOccurance(nums, 0, nums.Length - 1, target);
if (first == -1)
{
return new int[] { -1, -1 };
}
int last = this.GetLastOccurance(nums, 0, nums.Length - 1, target);
return new int[] { first, last };
}
private int GetFirstOccurance(int[] nums, int low, int high, int target)
{
if (low > high)
{
return -1;
}
int mid = (low + high) / 2;
if ((nums[mid] == target) && (mid == 0 || nums[mid] > nums[mid - 1]))
{
return mid;
}
else if (nums[mid] < target)
{
return this.GetFirstOccurance(nums, mid + 1, high, target);
}
else
{
return this.GetFirstOccurance(nums, low, mid - 1, target);
}
}
private int GetLastOccurance(int[] nums, int low, int high, int target)
{
if (low > high)
{
return -1;
}
int mid = (low + high) / 2;
if ((nums[mid] == target) && (mid == nums.Length - 1 || nums[mid] < nums[mid + 1]))
{
return mid;
}
else if (nums[mid] > target)
{
return this.GetLastOccurance(nums, low, mid - 1, target);
}
else
{
return this.GetLastOccurance(nums, mid + 1, high, target);
}
}
No comments:
Post a Comment