LeetCode 题解工作台

整数替换

给定一个正整数 n ,你可以做如下操作: 如果 n 是偶数,则用 n / 2 替换 n 。 如果 n 是奇数,则可以用 n + 1 或 n - 1 替换 n 。 返回 n 变为 1 所需的 最小替换次数 。 示例 1: 输入: n = 8 输出: 3 解释: 8 -> 4 -> 2 -> 1 示例 …

category

4

题型

code_blocks

4

代码语言

hub

3

相关题

当前训练重点

中等 · 状态·转移·动态规划

bolt

答案摘要

class Solution: def integerReplacement(self, n: int) -> int:

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 状态·转移·动态规划 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给定一个正整数 n ,你可以做如下操作:

  1. 如果 n 是偶数,则用 n / 2替换 n
  2. 如果 n 是奇数,则可以用 n + 1n - 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
lightbulb

解题思路

方法一

1
2
3
4
5
6
7
8
9
10
11
12
13
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
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • 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.

warning

常见陷阱

外企场景
  • 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.

swap_horiz

进阶变体

外企场景
  • 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.

help

常见问题

外企场景

整数替换题解:状态·转移·动态规划 | LeetCode #397 中等