LeetCode 题解工作台
加一
给定一个表示 大整数 的整数数组 digits ,其中 digits[i] 是整数的第 i 位数字。这些数字按从左到右,从最高位到最低位排列。这个大整数不包含任何前导 0 。 将大整数加 1,并返回结果的数字数组。 示例 1: 输入: digits = [1,2,3] 输出: [1,2,4] 解释:…
2
题型
7
代码语言
3
相关题
当前训练重点
简单 · 数组·数学
答案摘要
我们从数组的最后一个元素开始遍历,将当前元素加一,然后对 取模,如果取模后的结果不为 ,说明当前元素没有进位,直接返回数组即可。否则,当前元素为 ,需要进位,继续遍历前一个元素,重复上述操作。如果遍历完数组后,仍然没有返回,说明数组中所有元素都为 ,需要在数组的头部插入一个 。 时间复杂度 ,其中 是数组的长度。忽略答案的空间消耗,空间复杂度 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·数学 题型思路
题目描述
给定一个表示 大整数 的整数数组 digits,其中 digits[i] 是整数的第 i 位数字。这些数字按从左到右,从最高位到最低位排列。这个大整数不包含任何前导 0。
将大整数加 1,并返回结果的数字数组。
示例 1:
输入:digits = [1,2,3] 输出:[1,2,4] 解释:输入数组表示数字 123。 加 1 后得到 123 + 1 = 124。 因此,结果应该是 [1,2,4]。
示例 2:
输入:digits = [4,3,2,1] 输出:[4,3,2,2] 解释:输入数组表示数字 4321。 加 1 后得到 4321 + 1 = 4322。 因此,结果应该是 [4,3,2,2]。
示例 3:
输入:digits = [9] 输出:[1,0] 解释:输入数组表示数字 9。 加 1 得到了 9 + 1 = 10。 因此,结果应该是 [1,0]。
提示:
1 <= digits.length <= 1000 <= digits[i] <= 9digits不包含任何前导0。
解题思路
方法一:模拟
我们从数组的最后一个元素开始遍历,将当前元素加一,然后对 取模,如果取模后的结果不为 ,说明当前元素没有进位,直接返回数组即可。否则,当前元素为 ,需要进位,继续遍历前一个元素,重复上述操作。如果遍历完数组后,仍然没有返回,说明数组中所有元素都为 ,需要在数组的头部插入一个 。
时间复杂度 ,其中 是数组的长度。忽略答案的空间消耗,空间复杂度 。
class Solution:
def plusOne(self, digits: List[int]) -> List[int]:
n = len(digits)
for i in range(n - 1, -1, -1):
digits[i] += 1
digits[i] %= 10
if digits[i] != 0:
return digits
return [1] + digits
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(n) where n is the length of the digits array, as we may need to traverse the entire array in the worst case. Space complexity is O(1) if modified in-place, or O(n) if a new array is created. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Can the candidate handle the carry and array resizing efficiently?
- question_mark
Does the candidate consider all edge cases, including the case of multiple carries?
- question_mark
How well does the candidate optimize the solution in terms of space and time complexity?
常见陷阱
外企场景- error
Forgetting to handle carry-over when incrementing digits.
- error
Not properly adjusting the array length when a carry overflows the most significant digit.
- error
Overcomplicating the solution by using extra data structures unnecessarily.
进阶变体
外企场景- arrow_right_alt
What if the array represents a negative number? Adjust the approach accordingly.
- arrow_right_alt
How would the solution change if the number represented more than one digit per element (e.g., two-digit numbers per array element)?
- arrow_right_alt
How do you handle cases where the array is empty?