Algorithm interview from Google

前端 未结 8 496
囚心锁ツ
囚心锁ツ 2021-01-30 11:55

I am a long time lurker, and just had an interview with Google where they asked me this question:

Various artists want to perform at the Royal Albert Hall and you are re

8条回答
  •  星月不相逢
    2021-01-30 12:41

    I've used a binary search tree (BST) that holds the ranges for valid free days that can be scheduled for performances. One of the ranges must end with int.MaxValue, because we have an infinite amount of days so it can't be bound.

    The following code searches for the closest day to the requested day, and returns it.

    The time complexity is O(H) when H is the tree height (usually H=log(N), but can become H=N in some cases.). The space complexity is the same as the time complexity.

    public static int FindConcertTime(TreeNode> node, int reqDay)
    {
        // Not found!
        if (node == null)
        {
            return -1;
        }
        Tuple 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);
        }
    }
    

提交回复
热议问题