Backto Algo Index
上一篇说到了 Big-O 分析法, 但是那只适合分析复杂度随着 n n n 增大的趋势, 实际生产中, 我们还需要知道更细节的指标, 比如
- 最好情况时间复杂度 best case time complexity
- 最坏情况时间复杂度 worst case time complexity
- 平均情况时间复杂度 average case time complexity
- 均摊时间复杂度 amortized time complexity
Best, Worst & Average
先上代码
// n 表示数组 array 的长度
int find(int[] array, int n, int x) {
int i = 0;
int pos = -1;
for(; i < n; ++i) {
if(array[i] == x) {
pos = i;
break;
}
}
return pos;
}
很简单的, 在一个数组中 find 一个数是否存在, 逐一分析,
- Best case :
x = array[0]
, 一击即中, 复杂度 O ( 1 ) O(1) O(1) - Worst case :
x = array[n-1]
, 或者x not in array
, 那么需要找 n n n 次, 复杂度 O ( n ) O(n) O(n) - Average case : 平均就必要有意思了, 需要看你怎么分配权重, 或者说概率
- 均值分布, 一共有 n + 1 n+1 n+1