Abstract data type
Stack
Vector
Queue
Linked List
Priority Queue
Heap
Set
Hash Set
Tree Set
Map
Hash Map
Tree Map
Big O notation
O(1): Constant Complexity: Constant 常数复杂度
int n = 1000;
System.out.println("Hey - your input is: " + n);
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(log n): Logarithmic Complexity: 对数复杂度
for (int i = 1; i < n; i = i * 2) {
System.out.println("Hey - I'm busy looking at: " + i);
}
O(n): Linear Complexity: 线性时间复杂度
for (int = 1; i<=n; i++) {
System.out.println(“Hey - I'm busy looking at: " + i);
}
O(n^2): N square Complexity 平⽅
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(n^3): N square Complexity ⽴⽅
for (int i = 1; i <= n; i++) {
for (int j = 1; j <=n; j++) {
for (int j = 1; j <=n; j++) {
System.out.println("Hey - I'm busy looking at: "
+ i + " and " + j + " and " + k);
}
}
}
O(2^n): Exponential Growth 指数
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!): Factorial 阶乘
for (int i = 1; i <= factorial(n); i++){
System.out.println("Hey - I'm busy looking at: " + i);
}
example
为什么要关注时间复杂度呢,我们都知道 O(1) 的时间复杂度是最低的,执行时间也是最短的,我们写程序的时候也要尽量向O(1) 和 O(N)优化,了解了时间复杂度,我们也就了解了代码优化的方向
累加求和
1+2+...+n
O(N)的解法
let y = 0;
function add(n){for(let i = 1; i < n + 1; i++){
y = y + i
}
return y;
}
O(1) 的解法
function add(n){
return n * (n+1) / 2;
}
直接利用公式,不需要考虑 i 的初值和 循环结束时 n 的值,降低错误风险
斐波那契数列
F(n) = F(n-1) + F(n-2), 时间复杂度为 O(2^n), 左右两边会重复计算
Master Theorem
在算法分析中,支配理论(英语:master theorem)提供了用渐近符号(大O符号)表示许多由分治法得到的递推关系式的方法。