常用时间复杂度
O(1):没有循环和递归的,都是O(1)
function test(){
console.log('1111')
}
O(n):只有一层循环或递归的,都是O(n)
function test(n){
for(let i = 0;i<n;i++){
console.log('12121')
}
}
function test2(n){
while(--n > 0){
console.log('22222')
}
}
O(n²):里面循环执行n次,外层循环执行n次,总执行次数就是n X n,时间复杂度就是n的平方,也就是O(n²)
function test(n){
for(let i = 0;i<n;i++){
for(let j = 0;j<n;j++){
console.log('111111')
}
}
}
function test(n){
for(let j = 0;j<n;j++){
console.log('111111')
}
for(let i = 0;i<n;i++){
for(let j = 0;j<n;j++){
console.log('22222')
}
}
}
O(logn):循环次数的影响主要来源于n/2,时间复杂度就是 O(logn)
function test(n){
for (let i = 0; i < n; i *= 2){
console.log('11111')
}
}
test(16)
空间复杂度
定义:算法所需要多少内存,占用多少空间
O(1)
function test(){
console.log('11111')
}
O(n)
function test(n){
let arr = []
for(let i = 1;i < n;i++){
arr[i] = i
}
}
O(n²):一般出现在二维数组,或者矩阵
let arr = [
[1,2,3,4],
[3,2,3,4]
]