1.9 KiB
1.9 KiB
tags, create time
| tags | create time | |||
|---|---|---|---|---|
|
2026-05-15 15:30 |
01-MaxInt32-initial - math.MaxInt32 作为最小值搜索的初始值
背景
在寻找最小值的算法中(如最短路径、最短子串、最小距离等),需要用一个"足够大"的值作为初始最优解,确保第一次比较时任何实际值都能将其替换。
Go 中的正确做法
import "math"
bestLen := math.MaxInt32 // 使用整型的最大值作为初始"无穷大"
为什么用 math.MaxInt32?
| 错误做法 | 问题 |
|---|---|
999999 |
不够通用,当答案本身可能很大时会出错 |
-1 / 0 |
表示"未找到"而非"无穷大",无法用于 < 比较 |
math.MaxInt32 |
✅ 语言标准库提供,语义清晰,覆盖所有 int32 范围 |
典型使用场景
1. 最短覆盖子串
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. 最短路径 / 最小操作数
minSteps := math.MaxInt32
// BFS 或 DP 过程中不断更新 minSteps
if steps < minSteps {
minSteps = steps
}
注意事项
[!warning] ⚠️ 区分"未找到"与"无穷大"
math.MaxInt32 表示的是"当前没有找到可行解",而不是"无解"。判断是否无解需用另一个标记变量(如 bestStart == -1):
if bestStart == -1 {
return "" // 无解
}
return result[bestStart : bestStart+bestLen] // 有解
[!tip] 🔑 记忆口诀
找最小 → 初始设最大;找最大 → 初始设最小。 配合一个独立的 found 标记来区分"还没搜到"和"搜到了就是最大/最小"。