【发布时间】:2017-11-16 16:00:16
【问题描述】:
我刚刚参加了 Codility 演示测试。 question and my answer can be seen here,但我也会在这里粘贴我的答案。我的回应:
def solution(A):
# write your code in Python 2.7
retresult = 1; # the smallest integer we can return, if it is not in the array
A.sort()
for i in A:
if i > 0:
if i==retresult: retresult += 1 # increment the result since the current result exists in the array
elif i>retresult: break # we can go out of the loop since we found a bigger number than our current positive integer result
return retresult
我的问题是关于时间复杂度的,我希望通过您的回答能更好地理解这一点。该问题要求预期的最坏情况时间复杂度为 O(N)。
我的函数是否具有 O(N) 时间复杂度?我对数组进行排序这一事实是否会增加复杂性,如果是,如何增加?
Codility 报告(供我回答)
Detected time complexity:
O(N) or O(N * log(N))
那么,我的函数的复杂性是多少?如果是 O(N*log(N)),我该怎么做才能将复杂度降低到 O(N)?
非常感谢!
附言我对时间复杂度的背景阅读来自this great post。
编辑
在下面的回复和the answers described here for this problem 之后,我想用我对解决方案的看法对此进行扩展:
basicSolution 具有昂贵的时间复杂度,因此不是此 Codility 测试的正确答案:
def basicSolution(A):
# 0(N*log(N) time complexity
retresult = 1; # the smallest integer we can return, if it is not in the array
A.sort()
for i in A:
if i > 0:
if i==retresult: retresult += 1 #increment the result since the current result exists in the array
elif i>retresult: break # we can go out of the loop since we found a bigger number than our current positive integer result
else:
continue; # negative numbers and 0 don't need any work
return retresult
hashSolution 是我对上述文章“使用散列”段落中描述的内容的看法。由于我是 Python 新手,如果您对这段代码有任何改进(尽管它确实适用于我的测试用例),请告诉我,它的时间复杂度是多少?
def hashSolution(A):
# 0(N) time complexity, I think? but requires 0(N) extra space (requirement states to use 0(N) space
table = {}
for i in A:
if i > 0:
table[i] = True # collision/duplicate will just overwrite
for i in range(1,100000+1): # the problem says that the array has a maximum of 100,000 integers
if not(table.get(i)): return i
return 1 # default
最后,我无法理解实际的 0(N) 解决方案(O(n) 时间和 O(1) 额外空间解决方案)。我知道负/ 0 值被推到数组的后面,然后我们有一个只有正值的数组。但我不明白 findMissingPositive 功能 - 任何人都可以用 Python 代码/cmets 描述这个吗?也许举个例子?我一直在尝试在 Python 中解决它,但无法弄清楚:(
【问题讨论】: