[英]Is this code O(n) or O(logn)?
It's only checking the for loop 1/3n times, so it's still technically linear I guess? 它只检查for循环1 / 3n次,所以我猜它在技术上还是线性的吗? However I don't really understand why it wouldn't be O(logn), because many times a code with O(logn) running time ends up checking around 1/3n.
但是我真的不明白为什么它不是O(logn),因为很多时候运行时间为O(logn)的代码最终会检查1 / 3n左右。 Does O(logn) always divide the options by 2 every time?
O(logn)是否总是每次都将选项除以2?
int a = 0;
for (int i = 0; i < n; i = i+3)
a = a+i;
With time-complexity analysis, constant factors do not matter. 通过时间复杂度分析,恒定因素无关紧要。 You could do 1,000,000 operations per loop, and it will still be O(n).
您每个循环可以执行1,000,000次操作,但仍为O(n)。 Because the constant 1/3 doesn't matter, it's still O(n).
因为常数1/3无关紧要,所以它仍然是O(n)。 If you have
n
at 1,000,000, then 1/3 of n
would be much bigger than log n
. 如果
n
为1,000,000,那么n
1/3将比log n
大得多。
From the Wikipedia entry on Big-O notation : 从Wikipedia上关于Big-O符号的条目 :
Let k be a constant.
令k为常数。 Then:
然后:
O(kg) = O(g) if k is nonzero.
您的代码具有复杂度O(n), O(n)/3 == a * O(n) == O(n)
It is order of n O(n)
and not O(logn)
. 它是n
O(n)
顺序,而不是O(logn)
顺序。 It because the run time increases linearly with the increase in n
这是因为运行时间随
n
增加线性增加
For more information take a look at this graph and hopefully you will understand why it is not logn https://www.cs.auckland.ac.nz/software/AlgAnim/fig/log_graph.gif 有关更多信息,请查看此图,希望您能理解为什么未登录https://www.cs.auckland.ac.nz/software/AlgAnim/fig/log_graph.gif
运行时间为O(n)
(以单位复杂度度量)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.