简体   繁体   English

查找此方法的时间复杂度

[英]Finding the time complexity of this method

I am trying to figure out the time complexity of this code. 我试图弄清楚这段代码的时间复杂度。

My last conclusions about the sections is that the 'while' section the O(logn) the outer for loop must be under 100 so its O(1) and the inner for loop is O(logn) so i think that the time complexity here is O(logn) in the worst case but i am not sure. 我对这些部分的最后结论是,“ while”部分的O(logn)外部for循环必须小于100,因此其O(1)和内部for循环为O(logn),因此我认为此处的时间复杂度在最坏的情况下是O(logn),但我不确定。

public void foo (int n, int m) {
    int i = m;

    while (i > 100) {
        i = i/3;
    }

    for (int k=i ; k>=0; k--) {
        for (int j=1; j<n; j*=2) {
            System.out.print(k + "\t" + j);
        }

        System.out.println();
    }
}

Lets break your code step by step : 让我们逐步破坏您的代码:

The first loop ie, 第一个循环,即

 while (i > 100)  
     i = i/3;

runs O(logm) times. 运行O(logm)次。

for (int k=i ; k>=0; k--) { 
        for (int j=1; j<n; j*=2) {
            System.out.print(k + "\t" + j); 
        } //end inner for loop
        System.out.println(); 
    }

The outer loop can run atmost 100 times, and the inner loop ie 外循环最多可以运行100次,而内循环即

for (int j=1; j<n; j*=2) {
      System.out.print(k + "\t" + j); 
} //end inner for loop

executes logn times. 执行登录时间。

total time complexity of for loops = 100logn - > ignoring constants - > logn for循环的总时间复杂度= 100logn->忽略常量-> logn

Therefore, the complexity is O(log(m)) + O(log(n)) 因此,复杂度为O(log(m))+ O(log(n))

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

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