美文网首页算法和数据结构
3. 如何计算算法复杂度

3. 如何计算算法复杂度

作者: 博士伦2014 | 来源:发表于2018-11-21 09:40 被阅读35次

    总览

    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 + 2 + 3 + … + n (总共累加n次)
      y = 0
      for i = 1 to n:
      y = i + y
    • 求和公式:n(n+1)/2
      y = n * (n + 1) / 2

    1.3 What if recursion ?

    • Fibonacci array: 1, 1, 2, 3, 5, 8, 13, 21, 34, …
      F(n) = F(n-1) + F(n-2) : 2^n
    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

    相关文章

      网友评论

        本文标题:3. 如何计算算法复杂度

        本文链接:https://www.haomeiwen.com/subject/yedqqqtx.html