Big O notation

  • O(1): Constant Complexity: Constant 常数复杂度
  • O(log n): Logarithmic Complexity: 对数复杂度
  • O(n): Linear Complexity: 线性时间复杂度
  • O(n^2): N square Complexity 平⽅方
  • O(n^3): N square Complexity ⽴立⽅方
  • O(2^n): Exponential Growth 指数
  • O(n!): Factorial 阶乘

截屏2020-08-23 下午1.13.32.png

O(1)

  1. int n = 1000;
  2. System.out.println("Hey - your input is: " + n);
  3. // 下面的无论输出几条,是O(1)复杂度
  4. int n = 1000;
  5. System.out.println("Hey - your input is: " + n);
  6. System.out.println("Hmm.. I'm doing more stuff with: " + n);
  7. System.out.println("And more: " + n);

O(n)

一般单层循环都为O(n)。

  1. for (int = 1; i<=n; i++) {
  2. System.out.println(“Hey - I'm busy looking at: " + i);
  3. }

O(n^2)

嵌套的2次循环都为n,所以整体循环了n*n次,即:n^2次。

  1. for (int i = 1; i <= n; i++) {
  2. for (int j = 1; j <=n; j++) {
  3. System.out.println("Hey - I'm busy looking at: " + i + " and " + j);
  4. }
  5. }

O(log(n))

  1. for (int i = 1; i < n; i = i * 2) {
  2. System.out.println("Hey - I'm busy looking at: " + i);
  3. }

O(k^n)

  1. for (int i = 1; i <= Math.pow(2, n); i++){
  2. System.out.println("Hey - I'm busy looking at: " + i);
  3. }

O(n!)

  1. for (int i = 1; i <= factorial(n); i++){
  2. System.out.println("Hey - I'm busy looking at: " + i);
  3. }

例子:一个求和的计算的优化

求和:1+2+3+4+….+n

  1. // 时间复杂度为O(n)
  2. // 1+2+3+....+n (总共累加n次)
  3. sum =0;
  4. for (i=1,i<=n,i++){
  5. sum = i+sum;
  6. }
  7. // 时间复杂度为O(1)
  8. // 利用求和公式计算: n(n+1)/2
  9. sum = n * (n+1)/2

截屏2020-08-23 下午12.57.04.png