如何在ThreeSum.java中获得函数count和printall的时间复杂度?
public static void printAll(int[] a) {
int n = a.length;
for (int i = 0; i < n; i++) {
for (int j = i+1; j < n; j++) {
for (int k = j+1; k < n; k++) {
if (a[i] + a[j] + a[k] == 0) {
System.out.println(a[i] + " " + a[j] + " " + a[k]);
}
}
}
}
}
public static int count(int[] a) {
int n = a.length;
int count = 0;
for (int i = 0; i < n; i++) {
for (int j = i+1; j < n; j++) {
for (int k = j+1; k < n; k++) {
if (a[i] + a[j] + a[k] == 0) {
count++;
}
}
}
}
答案 0 :(得分:0)
虽然时间复杂度问题有时候很难,但这个问题很简单。您可以按照以下方式查看,
for (int i = 0; i < n; i++) // it runs for n times
for (int j = i+1; j < n; j++) // it runs for n-i-1 time
for (int k = j+1; k < n; k++) // it runs for n-j-1 times
现在,因为它们是嵌套循环,这意味着每个内循环运行的次数与外循环一样多。
total = n * ( n-i-1 ) * ( n-j-1 )
= n^3 ... // ignoring all other lower power terms
因此,此代码的时间复杂度为O(n^3)
。