虽然我只使用了一个循环,但我不认为代码的时间复杂度是O(n)。有人能解释一下下面代码的时间复杂性吗?
public class PatternPyramid {
public static void main(String[] args) {
int rows = 15;
int i = 0;
int j = 0;
int k = rows - 1;
while (i < rows) {
if (j < k) {
System.out.print(" ");
j++;
} else if (j < rows) {
j++;
System.out.print("* ");
} else {
j = 0;
i++;
k--;
System.out.println();
}
}
}
}发布于 2020-07-25 19:23:25
for (int i=0; i<rows; i++) {
for(int j=i; j<rows;j++)
System.out.print(" ");
for(int k=0; k<=i; k++)
System.out.print("* ");
System.out.println();
}您的代码可以转换为这样的for循环,因为可以看到外部循环运行O(行)次,空格的循环运行行--每次迭代运行i次,而星号循环运行I次。组合它们将导致内部循环运行行数次。
因此,总时间复杂度为O(行^2)。
https://stackoverflow.com/questions/63092263
复制相似问题