算法和数据结构

3. 如何计算算法复杂度

2018-11-21  本文已影响35人  博士伦2014

总览

image.png image.png

1. 时间复杂度 空间复杂度

1.1 Big O notation

-- What is Big O? --
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 阶乘

O(1) 常数复杂度

int n = 1000;
System.out.println("Hey - your input is: " + n);

O(?)

int n = 1000;
System.out.println("Hey - your input is: " + n);
System.out.println("Hmm.. I'm doing more stuff with: " + n);
System.out.println("And more: " + n);

O(n) 线性时间复杂度

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

O(n^2) 平方

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

O(log n) 对数复杂度

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

O(k^n) 指数

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

O(n!) 阶乘

for (int i = 1; i <= factorial(n); i++){
System.out.println("Hey - I'm busy looking at: " + i);
}
时间复杂度对比

1.2 To calculate: 1 + 2 + 3 + … + n

1.3 What if recursion ?

def fib(n):
 if n == 0 or n == 1:
   return n
 return fib(n - 1) + fib(n - 2)
Fib(6)

2. Master Theorem 主定律

需要掌握的常见算法复杂度

参考:
https://en.wikipedia.org/wiki/Master_theorem_(analysis_of_algorithms)
https://zh.wikipedia.org/wiki/%E4%B8%BB%E5%AE%9A%E7%90%86

上一篇下一篇

猜你喜欢

热点阅读