我使用了一个二叉搜索树 (BST),它保存了可以为表演安排的有效空闲天数的范围。其中一个范围必须以 int.MaxValue 结尾,因为我们有无限的天数,所以它不能被绑定。
以下代码搜索与请求日期最近的日期,并将其返回。
当 H 为树高时,时间复杂度为O(H) (通常为H=log(N),但在某些情况下可能变为H=N。)。空间复杂度与时间复杂度相同。
public static int FindConcertTime(TreeNode<Tuple<int, int>> node, int reqDay)
{
// Not found!
if (node == null)
{
return -1;
}
Tuple<int, int> currRange = node.Value;
// Found range.
if (currRange.Item1 <= reqDay &&
currRange.Item2 >= reqDay)
{
// Return requested day.
return reqDay;
}
// Go left.
else if (currRange.Item1 > reqDay)
{
int suggestedDay = FindConcertTime(node.Left, reqDay);
// Didn't find appropriate range in left nodes, or found day
// is further than current option.
if (suggestedDay == -1 || suggestedDay > currRange.Item1)
{
// Return current option.
return currRange.Item1;
}
else
{
// Return suggested day.
return suggestedDay;
}
}
// Go right.
// Will always find because the right-most node has "int.MaxValue" as Item2.
else //if (currRange.Item2 < reqDay)
{
return FindConcertTime(node.Right, reqDay);
}
}