How the time complexity of the following code is O(n)?

痞子三分冷 提交于 2019-12-04 06:17:55

问题


I was solving a time-complexity question on Interview Bit, which is given below in the image.

The correct answer to this question is O(N). But according to me, the answer should be O(NlogN). Since the complexity for the first "for loop" should be O(logN) because the variable i is divided by 2 in each iteration and I have studied that whenever the loop variables are either multiplied or divided by 2, then the time complexity is O(logN). Now, for the second "for loop", the complexity should be O(N), therefore, the final complexity should be O(N*logN).

Can anyone please explain where I am wrong?


回答1:


Do the actual math:

T(N) = N + N/2 + N/4 + ... + 1 (log_2 N terms in the sum)

This is a geometric series with ratio 1/2, so the sum is equal to:

T(N) = N*[1 - (1/2)^(log_2 N)] / (1 - 1/2) =
     = [N - N/(2^log_2 N)] / 0.5 =
     2^log_2 N = N
     = (N - 1) / 0.5 

So T(N) is O(N).



来源:https://stackoverflow.com/questions/42223300/how-the-time-complexity-of-the-following-code-is-on

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!