时间复杂度
- 用来衡量一个算法的运行速度,也就是程序运行的快慢
- 算法中的基本操作的执行次数,称为时间复杂度。
- 其中基本操作可能是++,可能是赋值,也可能是读取,也可能是打印...
- 基本操作的执行次数,不是精确的,使用大O渐近法表示,保留最高阶项,同时去掉系数,得到一个衡量时间复杂度的“近似值”
示例
1)计算func2的时间复杂度?
void func2(int N) {
int count = 0;
for (int k = 0; k < 2 * N ; k++) {
count++;
}
int M = 10;
while ((M--) > 0) {
count++;
}
System.out.println(count);
}
分析:基本操作为count++,所以要看执行了多少次count++,可以得到是 2*N+10,保留最高阶项后得到2N,再去掉系数得到结果为:O(N)
2)计算func3的时间复杂度?
void func3(int N, int M) {
int count = 0;
for (int k = 0; k < M; k++) {
count++;
}
for (int k = 0; k < N ; k++) {
count++;
}
System.out.println(count);
}
分析:基本操作为count++,执行了M+N次count++,结果为:O(M+N)
3)计算func4的时间复杂度?
void func4(int N) {
int count = 0;
for (int k = 0; k < 100; k++) {
count++;
}
System.out.println(count);
}
分析:基本操作为count++,执行了100次count++,结果为:O(1)
O(1)是常量复杂度,不一定只执行一次,也可能执行很多次。执行次数是固定的,和问题规模N无关,O(1)不一定比O(N)快
4)计算bubbleSort的时间复杂度
void bubbleSort(int[] array) {
for (int end = array.length; end > 0; end--) {
boolean sorted = true;
for (int i = 1; i < end; i++) {
if (array[i - 1] > array[i]) {
Swap(array, i - 1, i);
sorted = false;
}
}
if (sorted == true) {
break;
}
}
}
分析:基本操作为
一段代码的时间复杂度,重点考虑的是平均和最差的情况,最好的情况一般不考虑,设数组的长度为N,上面操作最差的情况执行了(N*(N-1))/2次,所以结果为O(N^2)
5)计算binarySearch的时间复杂度?
int binarySearch(int[] array, int value) {
int begin = 0;
int end = array.length - 1;
while (begin <= end) {
int mid = begin + ((end-begin) / 2);
if (array[mid] < value)
begin = mid + 1;
else if (array[mid] > value)
end = mid - 1;
else
return mid;
}
return -1;
}
分析:
在算法分析中logN表示底数为2,对数为N,有些地方也会写成lgN
6)计算阶乘递归factorial的时间复杂度?
long factorial(int N) {
return N < 2 ? N : factorial(N-1) * N;
}
分析:基本操作是方法调用/比较操作/相乘操作,基本操作递归了N次,结果为O(N)
7)计算斐波那契递归fibonacci的时间复杂度?
int fibonacci(int N) {
return N < 2 ? N : fibonacci(N-1)+fibonacci(N-2);
}
分析:基本操作递归了2^N,结果为O(2^N)
常见时间复杂度的快慢/大小
- O(1)
- O(logN)
- O(N)
- O(N*logN)
- O(N^2)
- O(N^3)
- O(2^N)
越往下,复杂度越高(考虑一个极端的N比较大的情况)