【发布时间】: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