简体   繁体   English

算法复杂度分析

[英]Algorithm complexity analysis

What's the big-O time complexity of the two methods listed below? 下面列出的两种方法的大O时间复杂度是多少?

Is method 1 O(log n²) or O(log n) ? 方法1是O(log n²)还是O(log n)

Is method 2 O(n²) or something else? 方法2是O(n²)还是其他?

public static void method1(int n) {
    int k = 0;      
    for (int i = 1; i <= n; i = i*2)
       for (int j = n; j > 1; j = j/2)
           k++;     
}               

public static void method2(int n) {             
    for (int i = 1; i <= n; i = i + 1)
       for (int j = i; j <= n; j++)
          method1(n);
}

In the first example, the outer loop executes logn times, and the second loop also executes log n times. 在第一个示例中,外部循环执行logn次,第二个循环也执行log n次。 The complexity is O(log² n). 复杂度为O(log²n)。

In the second example, the first loop executes n times and the second loop executes i times where i is the current index of the first loop. 在第二个示例中,第一个循环执行n次,第二个循环执行i次,其中i是第一个循环的当前索引。 So, it executes 1 + 2 + 3 + ... + n times, summing up to n ⋅ (n - 1) / 2. The resulting complexity is O( (n² - n)/2 ) = O(n²). 因此,它执行1 + 2 + 3 + ... + n次,总计为n⋅(n-1)/2。结果复杂度为O((n²-n)/ 2)= O(n²)。 Read more here 1 + 2 + 3 ... series 在这里阅读更多1 + 2 + 3 ...系列

So, to wrap it up, method2 executes method1 n² times, giving the total complexity of O(n² ⋅ log² n) 因此,总结起来,method2执行method1n²次,得出总复杂度为O(n²⋅log²n)

Well in the first method you have 2 nested loops where each one is exactly log(n) so yes that would turns them into a O((logn)^2) 好吧,在第一种方法中,您有2个嵌套循环,每个循环都恰好是log(n),因此可以将它们变成O((logn)^ 2)

For the second method, if we focus on the second loop we can see that for 对于第二种方法,如果我们关注第二个循环,则可以看到

  • i = 1 => runs n times i = 1 =>运行n次
  • i = 2 => runs n-1 times i = 2 =>运行n-1次
  • ... ...
  • i = n => runs 1 times i = n =>运行1次

This is an arithmetic progression and its sum is equal to n * (n+1) / 2 which turns it into an O((nlogn)^2) since we are calling method1 about n^2 times. 这是一个算术级数,它的总和等于n * (n+1) / 2 ,这使它变成O((nlogn)^ 2),因为我们调用method1大约n ^ 2次。

The complexity of method1 is O((log n)²) since we have a nested loop where each loop runs O(log n) times. 的复杂method1是O((log n)的²),因为我们每个循环运行Ø嵌套循环(log n)的时间。

In Method2 we execute Method1 a triangluar number of times, ie, we execute it O(n²) times. Method2 ,我们执行Method1一个triangluar号的时候,也就是我们执行它O(N²)次。 Since we execute an O((log n)²) function O(n²) times, the resulting complexity for Method2 is O(n² ⋅ (log n)²). 由于我们执行O((log n)的²)函数O(N²)次,将得到的复杂Method2是O(N²⋅(log n)的²)。

Methodically and formally, you can use Sigma notation like this: 您可以有条不紊地正式使用Sigma表示法,如下所示:

在此处输入图片说明

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

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