Home > Back-end >  Time complexity
Time complexity

Time:03-17


 
int i=0;
Int j=1;
i++;
j++;

This example is the complexity is O (1), won't increase with the increase of number of lines he, but no matter how many lines, no circulation,

2
 for (int I=0; iFor (int j=I; JSystem. The out. Println (" performs a "); 
}
}

Because there are two for loop, the time complexity is O (n2)

3
 int I=1; 
While (iI=I * 2;
}

Because with the increase of the number of the while loop, I gradually close to n, to exit the loop and so is 2 x equals n, calculate log2X time complexity is O (log2n), so as to O (logn) takes the base what, depends on what kind of digital times, this example is 2, if I=I * 3, the base is 3

Example 4

 for (int I=1; i<=n; I++) {
for(int j=1; J<=I; J++) {
For (int k=1; K<=j; K++) {
System. The out. Println (" performs a ");
}
}
}

3 for loop so is O (n3)

five
 for (int I=0; iSystem. The out. Println (" performs a "); 
}

The time complexity is O (n), because of cycle n + 1 times, why not a n time, because is not equal to also want to add to the judgment, and the n + 1 is approximately equal to n times, take the best time in counting number, and remove coefficient, time complexity is
  • Related