【问题标题】:What is the time and space complexity of the following program? - leetcode 1291以下程序的时间和空间复杂度是多少? - leetcode 1291
【发布时间】:2021-02-28 19:36:54
【问题描述】:

谁能告诉我答案的时间和空间复杂度是多少?

我认为时间复杂度是 O(nlogn) 假设这是排序函数需要多长时间。我还假设双 for 循环需要恒定的 O(1) 时间,因为数字字符串的长度不会改变。

我认为空间复杂度是 O(n),其中 n 是我们的结果数组中的元素数。但是,我不确定这个答案。

感谢任何帮助。

class Solution(object):
    def sequentialDigits(self, low, high):
        """
        :type low: int
        :type high: int
        :rtype: List[int]
        """
        numbers = "123456789" #every possible substring of this string represents the set of valid numbers that we can have
        
        results = []
        
        #get every substring from the 'number' string 
        for i in range(len(numbers)):
            for j in range(i, len(numbers)):
                # sustring in range i to j
                subString = numbers[i:j+1]
                
                #convert it to an integer
                subString= int(subString)
                
                #if its within the required range, add it to our array
                if low<=subString<=high:
                    results.append(subString)
                    
        return sorted(results)

【问题讨论】:

  • 最坏的情况是 O(n2) 其中 n 是数字的长度
  • @Ananth 并且 O(81) 是 O(1)。内部循环体独立于输入执行 45 次。
  • 但是数字字符串的长度 n 是恒定的吗?那为什么不能是 O(1)?
  • 提示:如果你翻转循环的顺序,你可以避免排序:首先搜索长度为 1 的字符串(从 1 开始),然后搜索长度为 2 的字符串,等等。
  • 是的,复杂度为 O(1),正如 @teekarna 所指出的那样。我建议不要使用 n 来描述数字字符串的长度,以免将其与输入的大小混淆,输入的大小也由 n 表示。在您的情况下,输入 n 的大小是 high 的值。

标签: python performance time-complexity


【解决方案1】:

算法的复杂度为 O(1)。大 O 表示法用于表示算法的渐近上限,因为输入大小 (n) 趋于无穷大。在这种特殊情况下,您的算法只能正确找到有限数量的可能解决方案 (45)。因此,最坏情况下的运行时间(或内存消耗)不取决于输入;你总是需要循环最多 45 个候选人。

【讨论】:

  • 由于 45 种可能是预先知道的,因此可以很容易地将它们硬编码到排序列表中。剩下的就是确定与lowhigh 的第一个和最后一个关系
【解决方案2】:

由于数字字符串的长度取决于输入的顺序。长度为 log10n。所以循环的时间复杂度将是 O( (log10n)2)。结果数组的最大长度将是数字字符串长度的平方,因此排序的时间复杂度将是 O( log10n( log( log10 n ) )。整体时间复杂度为 O( ( log10n)2 + log10n( log( log10n ) ) ) 简化为 O( log10n( log( log10n) ) ) ).

【讨论】:

  • 数字字符串被硬编码为“123456789”,因此它的长度固定为9。它完全不依赖于输入。
猜你喜欢
  • 2020-07-30
  • 1970-01-01
  • 2020-09-10
  • 1970-01-01
  • 2019-12-29
  • 2021-05-19
  • 1970-01-01
  • 2014-01-14
  • 1970-01-01
相关资源
最近更新 更多