递归函数的时空复杂度

问题描述 投票:0回答:1

这是来自这里的leetcode问题:https://leetcode.com/problems/reverse-string/solution/

写一个反转字符串的函数。输入字符串以字符数组char []的形式给出。]

不要为另一个数组分配额外的空间,必须通过使用O(1)额外的内存就地修改输入数组来做到这一点。

示例:

Input: ["h","e","l","l","o"]
Output: ["o","l","l","e","h"]

解决方案1:

class Solution:
    def reverseString(self, s):
        def helper(left, right):
            if left < right:
                s[left], s[right] = s[right], s[left]
                helper(left + 1, right - 1)

        helper(0, len(s) - 1)

时间复杂度:O(N)次执行N / 2交换的时间。空间复杂度:O(N)用于保留递归堆栈。

解决方案2:

class Solution:
    def reverseString(self, s):
        left, right = 0, len(s) - 1
        while left < right:
            s[left], s[right] = s[right], s[left]
            left, right = left + 1, right - 1

时间复杂度:O(N)交换N / 2个元素。空间复杂度:O(1),这是一个恒定的空间解决方案。

有人可以解释为什么解决方案2中的空间复杂度是O(1)而解决方案1中的空间复杂度是O(n)吗?

是因为解决方案1需要函数调用吗?

提前感谢!

这是来自此处的leetcode问题:https://leetcode.com/problems/reverse-string/solution/编写一个可反转字符串的函数。输入字符串以字符数组char []形式给出。做...

python recursion time-complexity space-complexity
1个回答
0
投票
© www.soinside.com 2019 - 2024. All rights reserved.