简体   繁体   English

为什么这个算法的时间是 O(n^2) 而不是 O(n^3)?

[英]Why does this algorithm have a O(n^2) time instead of O(n^3)?

I've been studying Big-O for an upcoming interview and I wanted something explained.我一直在为即将到来的面试学习 Big-O,我想解释一下。

So one way I've been determining the run-time of algorithms is by counting the number of for-loops.所以我一直在确定算法的运行时间的一种方法是计算 for 循环的数量。 For example, if an algorithm uses 1 for-loop I'd count that as O(n) and if it used two for-loops I'd say it was O(n^2).例如,如果一个算法使用 1 个 for 循环,我会将其计算为 O(n),如果它使用两个 for 循环,我会说它是 O(n^2)。 I find that this is generally an easy way to figure out time for simple algorithms.我发现这通常是计算简单算法时间的简单方法。 Although in a textbook I am reading they said this algorithm has an O(n^2) run-time.尽管在我正在阅读的教科书中,他们说该算法的运行时间为 O(n^2)。

 a=5
b=6
c=10
for i in range(n):
   for j in range(n):
      x = i * i
      y = j * j
      z = i * j
for k in range(n):
   w = a*k + 45
   v = b*b
d = 33

How would this have an O(n^2) run-time?这将如何有 O(n^2) 运行时间? If 𝑇(𝑛)=3+3𝑛2+2𝑛+1=3𝑛2+2𝑛+4 then are we just discarding the last loop (2n) because it does not add to 3n^2?如果𝑇(𝑛)=3+3𝑛2+2𝑛+1=3𝑛2+2𝑛+4 那么我们是否只是丢弃最后一个循环(2n),因为它没有添加到3n^2?

Thanks for reading!谢谢阅读!

Let's look at what the curves look like:让我们看看曲线是什么样的:

在此处输入图片说明

You can see here what a curve for just N looks like, along with the curve for N^2 and their sum.您可以在这里看到仅 N 的曲线是什么样的,以及 N^2 的曲线及其总和。 Notice anything?注意到什么了吗? The N^2+N curve looks a lot more like an N^2 curve than an N curve, adding the N didn't really change it a whole lot. N^2+N 曲线看起来更像 N^2 曲线而不是 N 曲线,添加 N 并没有真正改变它很多。 In fact, if we scale the sum curve by a constant (.93 in this case), we can make them look almost identical:事实上,如果我们通过一个常数(在本例中为 .93)来缩放和曲线,我们可以使它们看起来几乎相同:

在此处输入图片说明

If we're analyzing algorithms, at least theoretically, we're generally worried about the factors that will dominate our processing time.如果我们正在分析算法,至少在理论上,我们通常会担心影响我们处理时间的因素。 If adding a factor of N to the runtime doesn't change much, why bother thinking about it?如果将 N 的因子添加到运行时不会有太大变化,为什么还要考虑呢? We should worry about the quadratic behavior.我们应该担心二次行为。 This isn't necessarily true in real life, where we might really care if something is a constant 2x factor, but at least for theoretical analysis it is.这在现实生活中不一定是真的,在现实生活中我们可能真的很关心某个东西是否是一个恒定的 2 倍因子,但至少对于理论分析来说是这样。

This is why big-O notation is an asymptotic measure of performance.这就是为什么大 O 符号是性能的渐近度量。 We only consider what happens as N gets very large.我们只考虑当 N 变得非常大时会发生什么。 If we think about the ratio N^2/N as N -> infinity, it's obvious that this will trend to zero.如果我们将比率 N^2/N 视为 N -> 无穷大,很明显这将趋向于零。 So, the larger n gets, the less important the linear factor is, and thus we discard it.因此,n 越大,线性因子越不重要,因此我们将其丢弃。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM