简体   繁体   English

两个嵌套循环的运行时复杂度:二次还是线性?

[英]Running-time complexity of two nested loops: quadratic or linear?

int Solution::diffPossible(vector<int> &A, int B) {
    for (int i = 0; i < A.size(); i++) {
       for (int j = i+1; j < A.size(); j++)
          if ((A[j]-A[i]) == B)
             return 1;      
    }
    return 0;
}

This is the solution to a simple question where we are supposed to write a code with time complexity less than or equal to O(n). 这是一个简单问题的解决方案,在该问题中,我们应该编写时间复杂度小于或等于O(n)的代码。 I think the time complexity of this code is O(n^2) but still it got accepted. 我认为这段代码的时间复杂度为O(n ^ 2),但仍然被接受。 So, I am in doubt please tell me the right answer. 所以,我有疑问请告诉我正确的答案。

Let's analyze the worst-case scenario, ie when the condition of the if -statement in the inner loop, (A[j]-A[i]) == B , is never fulfilled, and therefore the statement return 1 is never executed. 让我们分析一下最坏的情况,即当的条件if语句来在内部循环, (A[j]-A[i]) == B ,是永远不会满足的,因此该语句return 1从不执行。

If we denote A.size() as n , the comparison in the inner loop is performed n-1 times for the first iteration of the outer loop, then n-2 times for the second iteration, and so on... 如果将A.size()表示为n ,则对内循环的比较对于外循环的第一次迭代执行n-1次,然后对第二次迭代进行n-2次,依此类推...

So, the number of the comparisons performed in the inner loop for this worst-case scenario is (by calculating the sum of the resulting arithmetic progression below): 因此,在此最坏情况下,在内部循环中执行的比较次数为(通过计算以下得出的算术级数之和):

n-1 + n-2 + ... + 1 = (n-1)n/2 = (n^2 - n)/2
^                 ^
|_________________|
     n-1 terms

Therefore, the running-time complexity is quadratic, ie, O(n^2), and not O(n). 因此,运行时复杂度是二次的,即O(n ^ 2),而不是O(n)。

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

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