# 01 | 复杂度分析（上）：如何分析、统计算法的执行效率和资源消耗？

### 大 O 复杂度表示法

```1 int cal(int n) {
2   int sum = 0;
3   int i = 1;
4   for (; i <= n; ++i) {
5     sum = sum + i;
6   }
7   return sum;
8 }
```

```1 int cal(int n) {
2   int sum = 0;
3   int i = 1;
4   int j = 1;
5   for (; i <= n; ++i) {
6     j = 1;
7     for (; j <= n; ++j) {
8       sum = sum +  i * j;
9     }
10   }
11 }
```

### 时间复杂度分析

1.只关注循环执行次数最多的一段代码

```1 int cal(int n) {
2   int sum = 0;
3   int i = 1;
4   for (; i <= n; ++i) {
5     sum = sum + i;
6   }
7   return sum;
8 }
```

2.加法法则：总复杂度等于量级最大的那段代码的复杂度

```int cal(int n) {
int sum_1 = 0;
int p = 1;
for (; p < 100; ++p) {
sum_1 = sum_1 + p;
}

int sum_2 = 0;
int q = 1;
for (; q < n; ++q) {
sum_2 = sum_2 + q;
}

int sum_3 = 0;
int i = 1;
int j = 1;
for (; i <= n; ++i) {
j = 1;
for (; j <= n; ++j) {
sum_3 = sum_3 +  i * j;
}
}

return sum_1 + sum_2 + sum_3;
}
```

3.乘法法则：嵌套代码的复杂度等于嵌套内外代码复杂度的乘积

```1int cal(int n) {
2   int ret = 0;
3   int i = 1;
4   for (; i < n; ++i) {
5     ret = ret + f(i);
6   }
7 }
8
9 int f(int n) {
10  int sum = 0;
11  int i = 1;
12  for (; i < n; ++i) {
13    sum = sum + i;
14  }
15  return sum;
16 }
```

1.O(1)

```1 int i = 8;
2 int j = 6;
3 int sum = i + j;
```

2.O(logn)、O(nlogn)

```1 i=1;
2 while (i <= n)  {
3   i = i * 2;
4 }
```

```1 i=1;
2 while (i <= n)  {
3   i = i * 3;
4 }
```

3.O(m+n)、O(m*n)

我们再来讲一种跟前面都不一样的时间复杂度，代码的复杂度由两个数据的规模来决定。老规矩，先看代码！

```int cal(int m, int n) {
int sum_1 = 0;
int i = 1;
for (; i < m; ++i) {
sum_1 = sum_1 + i;
}

int sum_2 = 0;
int j = 1;
for (; j < n; ++j) {
sum_2 = sum_2 + j;
}

return sum_1 + sum_2;
}
```

```1void print(int n) {
2  int i = 0;
3  int[] a = new int[n];
4  for (i; i <n; ++i) {
5    a[i] = i * i;
6  }

7  for (i = n-1; i >= 0; --i) {
8    print out a[i]
9  }
10}
```

### 内容小结

原文作者：Crazymagic
原文地址: https://www.cnblogs.com/crazymagic/p/9721619.html
本文转自网络文章，转载此文章仅为分享知识，如有侵权，请联系博主进行删除。