美文网首页算法和数据结构
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

相关文章

  • 2018-03-16 算法的复杂度

    算法的复杂度 初学者对算法的复杂度描述通常会产生疑惑,不知道如何去度量算法的复杂度。这次将介绍如何去计算算法的复杂...

  • 3. 如何计算算法复杂度

    总览 1. 时间复杂度 空间复杂度 1.1 Big O notation -- What is Big O? --...

  • 算法复杂度

    算法的复杂度是以什么来度量的? 算法的复杂度是以时间复杂度和空间复杂度来计算的。 ①算法的时间复杂度 ...

  • 算法初步

    时间复杂度 时间复杂度是用来估计算法运行时间的式子(单位)。 时间复杂度小结 空间复杂度 用来计算一个算法临时占用...

  • 算法的时间复杂度计算

    计算算法的时间复杂度,通常说的是算法的渐进增长时间复杂度,也就是随着数据的变大,该算法所需要的时间是如何增长的。 ...

  • 时间和空间复杂度

    算法复杂度 算法复杂度分为和。 时间复杂度是指执行算法所需要的计算工作量。 空间复杂度是指执行这个算法所需要的内存...

  • 排序算法

    数据结构8种排序时间和空间复杂度对比七大查找算法学了这么多年算法,你还不知道时间复杂度和空间复杂度如何计算吗?排序...

  • 算法的复杂度

    算法复杂度分为时间复杂度和空间复杂度。时间复杂度是指执行算法所需要的计算工作量,而空间复杂度是指执行这个算法所需要...

  • 时间复杂度 空间复杂度

    概念 时间复杂度和空间复杂度是用来衡量不同算法之间的优劣时间复杂度:计算的不是算法运行的时间,而是算法运行执行语句...

  • 复杂度分析(上)

    复杂度分析(上) 如何分析、统计算法的执行效率和资源消耗 数据结构和算法解决的是快 和 省的问题复杂度分析是整个算...

网友评论

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

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