LeetCode 题解工作台
整数替换
给定一个正整数 n ,你可以做如下操作: 如果 n 是偶数,则用 n / 2 替换 n 。 如果 n 是奇数,则可以用 n + 1 或 n - 1 替换 n 。 返回 n 变为 1 所需的 最小替换次数 。 示例 1: 输入: n = 8 输出: 3 解释: 8 -> 4 -> 2 -> 1 示例 …
4
题型
4
代码语言
3
相关题
当前训练重点
中等 · 状态·转移·动态规划
答案摘要
class Solution: def integerReplacement(self, n: int) -> int:
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 状态·转移·动态规划 题型思路
题目描述
给定一个正整数 n ,你可以做如下操作:
- 如果
n是偶数,则用n / 2替换n。 - 如果
n是奇数,则可以用n + 1或n - 1替换n。
返回 n 变为 1 所需的 最小替换次数 。
示例 1:
输入:n = 8 输出:3 解释:8 -> 4 -> 2 -> 1
示例 2:
输入:n = 7 输出:4 解释:7 -> 8 -> 4 -> 2 -> 1 或 7 -> 6 -> 3 -> 2 -> 1
示例 3:
输入:n = 4 输出:2
提示:
1 <= n <= 231 - 1
解题思路
方法一
class Solution:
def integerReplacement(self, n: int) -> int:
ans = 0
while n != 1:
if (n & 1) == 0:
n >>= 1
elif n != 3 and (n & 3) == 3:
n += 1
else:
n -= 1
ans += 1
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Understand dynamic programming and state transitions.
- question_mark
Identify efficient ways to optimize the problem using bit manipulation.
- question_mark
Evaluate the trade-offs between greedy approaches and memoization.
常见陷阱
外企场景- error
Not considering the optimal approach for odd numbers (subtract or add 1).
- error
Failing to memoize results, which can lead to redundant computations and inefficient solutions.
- error
Missing edge cases like n = 1 or n being a large number close to 231 - 1.
进阶变体
外企场景- arrow_right_alt
Extend the problem to handle non-positive integers.
- arrow_right_alt
Limit the number of operations or add constraints on the maximum allowed steps.
- arrow_right_alt
Explore a version where you must also track the exact sequence of operations taken.