1. 算法复杂度:是指算法在编写为可执行程序后运行所需的资源,包括时间资源和内存资源,分别用时间复杂度和空间复杂度描述。
2. big-O符号:(big O notation)代表“order of ...”(......阶),由德国数论学家Paul Bachmann于1892年著作中首先引入,其后由德国数论学家Edmund Landau推广,有时也称为朗道符号(Landau symbol)。描述函数的渐近行为,在CS中,在分析算法复杂度方面用处很大。
3. 算法复杂度影响因素:
- 算法采用的策略
- 编译代码质量
- 问题输入规模N
- 机器执行指令速度
一、时间复杂度
(1)时间频度:记为T(n),对算法程序中语句执行次数的描述,也称为语句频度。
(2)时间复杂度:记为O(n),对算法程序时间频度变化趋势的描述。当n趋近于无穷大时,若有某个辅助函数f(n),T(n)/f(n)为不等于0的常数,则T(n)=O(f(n)),这里f(n)称为T(n)的同数量级函数。
1. 常见算法复杂度(从小到大,from http://www.krivers.net/15112-s18/notes/notes-efficiency.html)
- 常数:O(1)
- 对数:O(logn)
- 方根:O(n^0.5)
- 线性:O(n)
- 准线性:O(nlogn)
- 平方:O(n^2)
- 指数:O(k^n)
2. python内置函数时间复杂度 (from http://www.krivers.net/15112-s18/notes/notes-efficiency.html)
General | ||
Function/Method | Complexity | Code Example |
O(N) | | |
Range in Iteration | Number of iterations = (end - start)/step | |
Strings: s is a string with N characters | ||
Function/Method | Complexity | Code Example |
Len | O(1) | |
Membership | O(N) | |
Get single character | O(1) | |
Get slice | O(end - start) | |
Get slice with step | O((end - start)/step) | |
Chr() and Ord() | O(1) | |
Concatentation | O(len(s1) + len(s2)) | |
Character Type Methods | O(N) | |
String Edit Methods | O(N) | |
Substring Search Methods | O(N) | |
Lists: L is a list with N elements | ||
Function/Method | Complexity | Code Example |
Len | O(1) | |
Append | O(1) | |
Extend | O(K) | |
Concatentation with += | O(K) | |
Concatentation with + | O(N + K) | |
Membership Check | O(N) | |
Pop Last Value | O(1) | |
Pop Intermediate Value | O(N) | |
Count values in list | O(N) | |
Insert | O(N) | |
Get value | O(1) | |
Set value | O(1) | |
Remove | O(N) | |
Get slice | O(end - start) | |
Get slice with step | O((end - start)/step) | |
Sort | O(N log (N)) | |
Multiply | O(N*D) | |
Minimum | O(N) | |
Maximum | O(N) | |
Copy | O(N) | |
Deep Copy | O(N*M) | |
Sets: s is a set with N elements | ||
Function/Method | Complexity | Code Example |
Len | O(1) | |
Membership | O(1) 原因在于:python中的set是基于哈希表实现的,这与dict一样,因此,计算elem的哈希函数获得地址,若地址存储的值=key,则查询成功,次过程不需要进行比较。 | |
Adding an Element | O(1) | |
Removing an Element | O(1) | |
Union | O(len(s) + len(t)) | |
Intersection | O(min(len(s), len(t))) | |
Difference | O(len(s)) | |
Clear | O(len(s)) | |
Copy | O(len(s)) | |
Dictionaries: d is a dictionary with N key-value pairs | ||
Function/Method | Complexity | Code Example |
Len | O(1) | |
Membership | O(1) | |
Get Item | O(1) | |
Set Item | O(1) | |
Delete Item | O(1) | |
Clear | O(N) | |
Copy | O(N) | |