如何找到 3Sum.java 的渐近复杂度
How to find the asymptotic complexity of 3Sum.java
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++;
}
}
}
}
虽然时间复杂度问题有时很难,但这道题很简单。您可以通过以下方式简单查看,
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)
。
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++;
}
}
}
}
虽然时间复杂度问题有时很难,但这道题很简单。您可以通过以下方式简单查看,
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)
。