一些选择题,会给一小段代码,求时间复杂度。
或者有些代码写完,会要求分析时间复杂度。
这里写一些例子,以后遇到不断补充。
基本的
1 – Constant Time
look up table (hashtable)
如果是完美hash,则worst是O(1)
如果不是完美hash,则worst是O(n)
on average, O(1)
log (log N)
Shrinking by a Square Root
procedure A(n)
begin
if (n < 3)
return 1
else
return A(ceiling(sqrt(n)))
end
end
log N – Logarithmic Time
reduces the size of the input data in each step
- operations on 二叉树Binary Tree
- 二分搜索Binary Search
int a = 1;
while (a < n) {
a = a * 2;
}
N – Linear Time
N * log N – Quasilinear Time
排序算法:
- 归并排序merge sort
- 快速排序quick sort
- 堆排序heap sort
- 希尔排序
void quicksort(int list[], int left, int right)
{
int pivot = partition(list, left, right);
quicksort(list, left, pivot - 1);
quicksort(list, pivot + 1, right);
}
Amortized time per operation using a bounded priority queue (from wiki)
N2 – Quadratic Time
finding all subsets of a set: 0(2^n) —>n个元素,每个都可以”选“/”不选“,222*…*2 (共n个)
排序算法:
- 冒泡排序Bubble sort
- 插入排序Insert sort
2n – Exponential Time
growth doubles with each addition to the input data set
- Find all subsets
def fibonacci(n):
if n <= 1:
return n
return fibonacci(n-1) + fibonacci(n-2)
N!
finding all permutations of a string: 0(n!) —>n个位置,第一个位置有n种选择,第二个位置n-1中,…,n*(n-1)(n-2)…21
- the Heap’s algorithm, which is used for generating all possible permutations of n objects. 原文
def heap_permutation(data, n):
if n == 1:
print(data)
return
for i in range(n):
heap_permutation(data, n - 1)
if n % 2 == 0:
data[i], data[n-1] = data[n-1], data[i]
else:
data[0], data[n-1] = data[n-1], data[0]
if __name__ == '__main__':
data = [1, 2, 3]
heap_permutation(data, len(data))
- Travelling salesman problem
Big-O Cheat Sheet
graph
下图摘自这里
复合的
有些code snippet是两种函数交织在一起,互相传input/output。