说明
时间复杂度分为:
常数阶O(1)>对数阶O(logN)>线性阶O(N)>线性对数阶O(NlogN)>平方阶O(N^2)>乘阶O(N!)>指数阶O(2^N)
复杂多就是套用最深的语句,所执行的次数表示。复杂度越高的算法,执行的次数就越多,所需要的时间就会越多
在开发过程中,编写程序时关注时间复杂度和空间复杂度两个维度,业务逻辑不变的情况下减少时间复杂度,可以提升执行的性能
举例
常数阶
int algorithm(int N) {
int count = 0;
int a = 10000;
for (int i = 0; i < a; i++) {
count++; 10000次=O(10000) =O(1)
}
return count;
}
对数阶
int algorithm(int N) {
int count = 0;
float i = N;
while (i > 1) {
i = i / 2;
count++; n/2 =O(logN)
}
return count;
}
线性阶
int algorithm(int N) {
int count = 0;
for (int i = 0; i < N; i++)
count++; n = O(N)
return count;
}
线性对数阶
int algorithm(int N) {
int count = 0;
float i = N;
while (i > 1) {
i = i / 2; n/2
for (int j = 0; j < N; j++)
count++; n/2 * n =O(logN)*O(N)=O(NlogN)
}
return count;
}
平方阶
int algorithm(int N) {
int count = 0;
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) { n
count++; n * n =O(N)*O(N)=O(N^2)
}
}
return count;
}
乘阶
int algorithm(int N) {
if (N <= 0) return 1;
int count = 0;
for (int i = 0; i < N; i++) {
count += algorithm(N - 1); n * n-1 * n-2...=O(N!)
}
return count;
}
指数阶
int algorithm(int N) {
if (N <= 0) return 1;
int count_1 = algorithm(N - 1);
int count_2 = algorithm(N - 1);
return count_1 + count_2; 2^0 2^1 .....2^n =O(2^N)
}