python函数做n_简单Python函数的O(N)时间复杂性
我剛做了一個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來完成它,但是無法理解它:(
總結
以上是生活随笔為你收集整理的python函数做n_简单Python函数的O(N)时间复杂性的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: linux查端口被占用情况,Linux系
- 下一篇: python网页登录验证码不显示_进网页