Files
leetcode-go/note/2026-05-15/01-MaxInt32-initial.md
T

75 lines
1.9 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
---
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 标记来区分"还没搜到"和"搜到了就是最大/最小"。