# 时间复杂度

# 是什么?

  • 一个函数,用大 O 表示,比如 O(1)、O(n)、O(logN)...
  • 定性描述该算法的时间

O(1)

// O(1)
let i = 0
i += 1
1
2
3

O(n)

// O(n)
for (let i = 0; i < n; i += 1) {
  console.log(i)
}
1
2
3
4

O(n)+O(1)=O(n)

// O(n)+O(1)=O(n)
let i = 0
i += 1
for (let j = 0; j < n; j += 1) {
  console.log(j)
}
1
2
3
4
5
6

O(n)*O(n)=O(n^2)

// O(n)*O(n)=O(n^2)
for (let i = 0; i < n; i += 1) {
  for (let j = 0; j < n; j += 1) {
    console.log(i, j)
  }
}
1
2
3
4
5
6

O(n)*O(n)=O(n^2)

// O(n)*O(n)=O(n^2)
for (let i = 0; i < n; i += 1) {
  for (let j = 0; j < n; j += 1) {
    console.log(i, j)
  }
}
1
2
3
4
5
6

O(logN)

// O(logN)
let i = 1
while (i > n) {
  console.log(i)
  i *= 2
}
1
2
3
4
5
6
Last Updated: 3/25/2024, 5:09:19 PM