vault backup: 2026-05-15 16:23:08

This commit is contained in:
2026-05-15 16:23:08 +08:00
parent c5d8fdac92
commit 2768d4eeb4
4 changed files with 497 additions and 0 deletions
+74
View File
@@ -0,0 +1,74 @@
---
tags: ["Go", "算法技巧", "初始化"]
create time: 2026-05-15 15:30
---
# 01-MaxInt32-initial - math.MaxInt32 作为最小值搜索的初始值
## 背景
在**寻找最小值**的算法中(如最短路径、最短子串、最小距离等),需要用一个"足够大"的值作为初始最优解,确保第一次比较时任何实际值都能将其替换。
## Go 中的正确做法
```go
import "math"
bestLen := math.MaxInt32 // 使用整型的最大值作为初始"无穷大"
```
### 为什么用 `math.MaxInt32`?
| 错误做法 | 问题 |
|---------|------|
| `999999` | 不够通用,当答案本身可能很大时会出错 |
| `-1` / `0` | 表示"未找到"而非"无穷大",无法用于 `<` 比较 |
| `math.MaxInt32` | ✅ 语言标准库提供,语义清晰,覆盖所有 int32 范围 |
## 典型使用场景
### 1. 最短覆盖子串
```go
bestStart, bestLen := -1, math.MaxInt32
for right, char := range s {
// ... expand / shrink logic ...
for formed == required {
currentLen := right - left + 1
if currentLen < bestLen { // 任何合法长度都 < MaxInt32
bestStart = left
bestLen = currentLen
}
// ...
}
}
```
### 2. 最短路径 / 最小操作数
```go
minSteps := math.MaxInt32
// BFS 或 DP 过程中不断更新 minSteps
if steps < minSteps {
minSteps = steps
}
```
## 注意事项
> [!warning] ⚠️ 区分"未找到"与"无穷大"
`math.MaxInt32` 表示的是"当前没有找到可行解",而不是"无解"。判断是否无解需用另一个标记变量(如 `bestStart == -1`):
```go
if bestStart == -1 {
return "" // 无解
}
return result[bestStart : bestStart+bestLen] // 有解
```
> [!tip] 🔑 记忆口诀
> **找最小 → 初始设最大;找最大 → 初始设最小。**
> 配合一个独立的 found 标记来区分"还没搜到"和"搜到了就是最大/最小"。