> For the complete documentation index, see [llms.txt](https://docs.1l.lol/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.1l.lol/complexity-debug/time-complexity.md).

# 时间复杂度

### 什么是时间复杂度

时间复杂度描述算法运行时间随**数据规模 n** 增长的趋势，用大 O 表示，只看**最高阶项**，忽略常数。

### 常见复杂度

| 复杂度        | 含义   | n=10⁵ 时大致运算次数 |
| ---------- | ---- | ------------- |
| O(1)       | 常数   | 1             |
| O(log n)   | 对数   | ≈ 17          |
| O(n)       | 线性   | 10⁵           |
| O(n log n) | 线性对数 | ≈ 1.7×10⁶     |
| O(n²)      | 平方   | 10¹⁰（超时）      |
| O(2ⁿ)      | 指数   | 不可行           |

### 怎么数循环

```cpp
for (int i = 0; i < n; i++) cnt++;         // O(n)
for (int i = 0; i < n; i++)
    for (int j = 0; j < n; j++) cnt++;     // O(n²)
for (int i = 1; i <= n; i *= 2) cnt++;     // O(log n)
```

* 顺序执行取**相加**再取最大项。
* 嵌套循环取**相乘**。
* 循环按固定步长减半（`i *= 2`、`i /= 2`）通常是 O(log n)。

### 根据数据范围选算法

| n 的范围    | 可用复杂度           |
| -------- | --------------- |
| n ≤ 20   | O(2ⁿ)、O(n!)     |
| n ≤ 1000 | O(n²)           |
| n ≤ 10⁵  | O(n log n)      |
| n ≤ 10⁶  | O(n)            |
| n ≤ 10⁹  | O(log n) 或 O(1) |

一般 1 秒大约能做 `10^8` 次简单运算，估算时以此为准。

### 空间复杂度

同理衡量额外内存随 n 的变化，如开一个长度 n 的数组是 O(n)，二维数组 O(n²)。


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.1l.lol/complexity-debug/time-complexity.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
