Files
interview/16-LeetCode Hot 100/两数相加.md
yasinshaw 4247e0700d refactor: convert all LeetCode solutions to Go-only
Changes:
- Removed all Java code implementations
- Kept only Go language solutions
- Renamed "## Go 解法" to "## 解法"
- Removed "### Go 代码要点" sections
- Cleaned up duplicate headers and empty sections
- Streamlined documentation for better readability

Updated files (9):
- 三数之和.md
- 两数相加.md
- 无重复字符的最长子串.md
- 最长回文子串.md
- 括号生成.md
- 子集.md
- 单词搜索.md
- 电话号码的字母组合.md
- 柱状图中最大的矩形.md

All 22 LeetCode Hot 100 Medium problems now use Go exclusively.
Code is cleaner, more focused, and easier to follow.

Generated with [Claude Code](https://claude.ai/code)
via [Happy](https://happy.engineering)

Co-Authored-By: Claude <noreply@anthropic.com>
Co-Authored-By: Happy <yesreply@happy.engineering>
2026-03-05 12:32:55 +08:00

120 lines
2.8 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.
# 两数相加 (Add Two Numbers)
LeetCode 2. Medium
## 题目描述
给你两个 **非空** 的链表,表示两个非负的整数。它们每位数字都是按照 **逆序** 的方式存储的,并且每个节点只能存储 **一位** 数字。
请你将两个数相加,并以相同形式返回一个表示和的链表。
你可以假设除了数字 0 之外,这两个数都不会以 0 开头。
**示例 1**
```
输入l1 = [2,4,3], l2 = [5,6,4]
输出:[7,0,8]
解释342 + 465 = 807
```
**示例 2**
```
输入l1 = [0], l2 = [0]
输出:[0]
```
**示例 3**
```
输入l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]
输出:[8,9,9,9,0,0,0,1]
```
## 解题思路
### 核心思想
模拟竖式加法,同时遍历两个链表,逐位相加并处理进位。
### 算法流程
1. 初始化哑节点和进位 carry = 0
2. 同时遍历两个链表:
- 计算当前位的和sum = l1.val + l2.val + carry
- 更新进位carry = sum / 10
- 创建新节点sum % 10
3. 处理最后的进位
4. 返回结果链表
### 复杂度分析
- **时间复杂度**O(max(m, n))m 和 n 分别为两个链表的长度
- **空间复杂度**O(1),不考虑结果链表的空间
---
---
## 进阶问题
### Q1: 如果链表是正序存储的,如何解决?
**方法**:反转链表 + 上述算法,或使用栈
```go
func addTwoNumbersReverse(l1, l2 *ListNode) *ListNode {
// 反转链表
l1 = reverseList(l1)
l2 = reverseList(l2)
// 使用相同算法相加
result := addTwoNumbers(l1, l2)
// 反转结果
return reverseList(result)
}
func reverseList(head *ListNode) *ListNode {
var prev *ListNode
for head != nil {
next := head.Next
head.Next = prev
prev = head
head = next
}
return prev
}
```
### Q2: 如何处理多个链表相加?
**方法**:逐个相加或使用优先队列(最小堆)
---
## P7 加分项
### 深度理解
- **链表操作**:指针移动、内存管理
- **边界处理**:不同长度链表、最后进位
- **哑节点技巧**:简化代码逻辑
### 实战扩展
- **大数据场景**:链表表示超大整数相加
- **分布式场景**MapReduce 实现大数相加
- **面试追问**:时间复杂度能否优化?如何测试?
### 变形题目
1. [445. 两数相加 II](https://leetcode.cn/problems/add-two-numbers-ii/) - 链表正序存储
2. [链表相加系列](https://leetcode.cn/tag/linked-list/) - 更多链表操作
---
## 总结
这道题的核心是:
1. **模拟加法**:逐位相加,处理进位
2. **链表遍历**:同时遍历两条链表
3. **边界处理**:不同长度、最后进位
**易错点**
- 忘记处理最后的进位
- 链表长度不一致时的处理
- 哑节点的使用(简化代码)
**最优解法**:一次遍历,时间 O(max(m,n)),空间 O(1)