我刚做了一个Codibility演示测试。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)时间复杂度吗?我对数组进行排序是否会增加复杂性,如果是,如何增加复杂性?在
Codibility报告(供我回答)
^{pr2}$
那么,我的函数的复杂性是什么呢?如果是O(N*log(N)),我该怎么做才能将问题的复杂度降低到O(N)?在
非常感谢!在
另外,我对时间复杂性的背景阅读来自this great post。在
编辑
基本解决方案具有昂贵的时间复杂度,因此不是此可信性测试的正确答案: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代码/注释来描述这个函数吗?举个例子吧?我一直在尝试用Python来完成它,但是无法理解它:(