LeetCode 题解工作台
插入后的最大值
给你一个非常大的整数 n 和一个整数数字 x ,大整数 n 用一个字符串表示。 n 中每一位数字和数字 x 都处于闭区间 [1, 9] 中,且 n 可能表示一个 负数 。 你打算通过在 n 的十进制表示的任意位置插入 x 来 最大化 n 的 数值 。但 不能 在负号的左边插入 x 。 例…
2
题型
7
代码语言
3
相关题
当前训练重点
中等 · 贪心·invariant
答案摘要
如果 是负数,那么我们要找到第一个大于 的位置,然后在这个位置插入 ;如果 是正数,那么我们要找到第一个小于 的位置,然后在这个位置插入 。 时间复杂度 ,其中 为 的长度。空间复杂度 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 贪心·invariant 题型思路
题目描述
给你一个非常大的整数 n 和一个整数数字 x ,大整数 n 用一个字符串表示。n 中每一位数字和数字 x 都处于闭区间 [1, 9] 中,且 n 可能表示一个 负数 。
你打算通过在 n 的十进制表示的任意位置插入 x 来 最大化 n 的 数值 。但 不能 在负号的左边插入 x 。
- 例如,如果
n = 73且x = 6,那么最佳方案是将6插入7和3之间,使n = 763。 - 如果
n = -55且x = 2,那么最佳方案是将2插在第一个5之前,使n = -255。
返回插入操作后,用字符串表示的 n 的最大值。
示例 1:
输入:n = "99", x = 9 输出:"999" 解释:不管在哪里插入 9 ,结果都是相同的。
示例 2:
输入:n = "-13", x = 2 输出:"-123" 解释:向 n 中插入 x 可以得到 -213、-123 或者 -132 ,三者中最大的是 -123 。
提示:
1 <= n.length <= 1051 <= x <= 9n 中每一位的数字都在闭区间[1, 9]中。n代表一个有效的整数。- 当
n表示负数时,将会以字符'-'开始。
解题思路
方法一:贪心
如果 是负数,那么我们要找到第一个大于 的位置,然后在这个位置插入 ;如果 是正数,那么我们要找到第一个小于 的位置,然后在这个位置插入 。
时间复杂度 ,其中 为 的长度。空间复杂度 。
class Solution:
def maxValue(self, n: str, x: int) -> str:
i = 0
if n[0] == "-":
i += 1
while i < len(n) and int(n[i]) <= x:
i += 1
else:
while i < len(n) and int(n[i]) >= x:
i += 1
return n[:i] + str(x) + n[i:]
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
They mention that n is stored as a string because numeric conversion is unsafe at this size.
- question_mark
They hint that the negative case is the same scan shape but with the opposite comparison rule.
- question_mark
They care about the first valid insertion point, which is the greedy invariant that makes later positions suboptimal.
常见陷阱
外企场景- error
Using the positive-number rule on negative input and inserting before a smaller digit instead of a larger one.
- error
Trying every insertion position and comparing full candidate strings, which is unnecessary and too slow for n.length up to 10^5.
- error
Converting n into an integer type, which can overflow and also ignores that this is a string-order greedy problem.
进阶变体
外企场景- arrow_right_alt
Return the minimum value after insertion instead of the maximum, which flips the comparison rule for both signs.
- arrow_right_alt
Insert a digit into a non-negative decimal string with leading-zero rules, where the insertion condition must respect formatting constraints.
- arrow_right_alt
Insert multiple digits from a second string, where the single-step greedy rule becomes a merge-style decision process.