简体   繁体   English

大O-O(N ^ 2)或O(N ^ 2 +1)吗?

[英]Big O - O(N^2) or O(N^2 + 1)?

I'm reading this Big O article (and some other book references) trying to figure out what changes affect my algorithm. 我正在阅读这篇 Big O文章(以及其他一些参考书),试图找出哪些变化会影响我的算法。

so given the following O(N^2) code: 因此,给出以下O(N ^ 2)代码:

bool ContainsDuplicates(String[] strings)
{
    for(int i = 0; i < strings.Length; i++)
    {
        for(int j = 0; j < strings.Length; j++)
        {
            if(i == j) // Don't compare with self
            {
                continue;
            }

            if(strings[i] == strings[j])
            {
                return true;
            }
        }
    }
    return false;
}

I made the following change: 我进行了以下更改:

bool ContainsDuplicates(String[] strings)
{
    for(int i = 0; i < strings.Length; i++)
    {
        for(int j = 0; j < strings.Length; j++)
        {
            if(i != j) // Don't compare with self
            {                               

                   if(strings[i] == strings[j])
                   {
                      return true;
                   }
            }
        }
    }
    return false;
}

Now both IF's are nested and 'continue' is removed. 现在,两个IF都嵌套了,并且删除了“ continue”。 Does this algorithm really became a O(N^2 + 1) ? 这个算法真的变成O(N ^ 2 +1)吗? and why ? 为什么? As far as I see the IF check was there before regardless, so initially thought it would still be a O(N^2). 据我所知,之前无论如何都存在IF检查,因此最初认为它仍然是O(N ^ 2)。

Big O is describing how execution time grows as a chosen parameter becomes large. 大O描述的是执行时间如何随着所选参数变大而增加。

In your example, if we wanted to be exact, the formula would be: 在您的示例中,如果我们想要精确,则公式为:

Time taken = Time(start) + Time(external loop) * N + Time (continue) * N + Time (no continue) * N^2 花费的时间=时间(开始)+时间(外部循环)* N +时间(连续)* N +时间(不继续)* N ^ 2

Which can be rewritten as 可以改写成

Time taken = a + b * N + c * N^2 花费的时间= a + b * N + c * N ^ 2

Now, as N becomes larger and larger, it's clear that overall this will be shaped like a parabola. 现在,随着N变得越来越大,很明显,总体而言,它的形状将像抛物线。 The order zero and order one terms become irrelevant as N grows to infinity. 随着N增长到无穷大,零阶和一阶项变得无关紧要。

Time taken (large N) ~= c * N^2 花费的时间(大N)〜= c * N ^ 2

Finally, since we are interested in discussing qualitatively and not quantitatively , we simply describe the algorirhm as N^2 最后,由于我们对定性讨论而不是定量讨论感兴趣,因此我们将算法简单地描述为N ^ 2

O(N^2) means that the algorithm will behave approximately as c * N^2 for large values of N O(N ^ 2)表示对于大的N值,该算法的行为近似为c * N ^ 2

It is a similar concept to o(x) in calculus (with the difference that small-o is for parameters going to zero. 它与微积分中的o(x)类似(不同之处在于small-o用于参数变为零)。

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

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