如何计算递归函数的时间和空间复杂度?

时间:2019-01-24 21:38:19

标签: python recursion time-complexity space-complexity

我目前正在练习面试问题。问题是:

Given an integer array with no duplicates. A maximum tree building on this array is defined as follow: 
    1. The root is the maximum number in the array. 
    2. The left subtree is the maximum tree constructed from left part subarray divided by the maximum number.
    3. The right subtree is the maximum tree constructed from right part subarray divided by the maximum number.

Construct the maximum tree by the given array and output the root node of this tree. 

我对这个问题的解决方案是:

def constructMaximumBinaryTree(nums):
        """
        :type nums: List[int]
        :rtype: TreeNode
        """
        if nums:
            maxIdx = nums.index(max(nums))
            root = TreeNode(nums[maxIdx])
            left = constructMaximumBinaryTree(nums[:maxIdx])
            right = constructMaximumBinaryTree(nums[maxIdx + 1:])
            root.left = left
            root.right = right
            return root

我知道它是如何工作的,但是我不确定如何计算时间和空间的复杂性。如果我尝试绘制解决方案,则对于每个节点,输入数组都会分为两部分,直到其为空。因此,我猜想像是O(log n),但我不确定确切的推理。空间复杂度相同。有提示吗?

1 个答案:

答案 0 :(得分:0)

否,不一定是 O(n log n)

首先,考虑递归过程本身:拆分决定的最坏情况(“复杂性”的默认解释)位置是什么?如果给定数组已排序,则最大元素始终在末尾,并且递归退化为每次迭代都删除一个元素的过程。

第二,考虑一次传递函数的复杂性,除了递归。您的序列中每个操作的复杂性是什么?

  • 找到列表中的max
  • 在列表中找到元素
  • 构造节点
  • 切片列表
  • 全部发挥作用
  • 切片列表
  • 函数调用
  • 分配
  • 分配
  • 返回根节点

其中许多是 O(1)操作,但有一些是 O(n)-其中n的长度当前列表,而不是原始列表。

这将导致最坏情况的 O(n ^ 2)。如您所知,最佳情况是 O(n log n),假设输入的树是完美平衡的。平均情况...您可能不再需要它了,但是它是 O(n log n),且常数较差。