LeetCode 题解工作台

坏了的计算器

在显示着数字 startValue 的坏计算器上,我们可以执行以下两种操作: 双倍(Double): 将显示屏上的数字乘 2; 递减(Decrement): 将显示屏上的数字减 1 。 给定两个整数 startValue 和 target 。返回显示数字 target 所需的最小操作数。 示例 1:…

category

2

题型

code_blocks

5

代码语言

hub

3

相关题

当前训练重点

中等 · 贪心·invariant

bolt

答案摘要

我们可以采用逆向计算的方式,从 开始,如果 是奇数,那么 $\textit{target} = \textit{target} + 1$,否则 $\textit{target} = \textit{target} / 2$,累加操作次数,直到 $\textit{target} \leq \textit{startValue}$,此时的操作次数加上 $\textit{startValue} - …

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 贪心·invariant 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

在显示着数字 startValue 的坏计算器上,我们可以执行以下两种操作:

  • 双倍(Double):将显示屏上的数字乘 2;
  • 递减(Decrement):将显示屏上的数字减 1

给定两个整数 startValue 和 target 。返回显示数字 target 所需的最小操作数。

 

示例 1:

输入:startValue = 2, target = 3
输出:2
解释:先进行双倍运算,然后再进行递减运算 {2 -> 4 -> 3}.

示例 2:

输入:startValue = 5, target = 8
输出:2
解释:先递减,再双倍 {5 -> 4 -> 8}.

示例 3:

输入:startValue = 3, target = 10
输出:3
解释:先双倍,然后递减,再双倍 {3 -> 6 -> 5 -> 10}.

 

提示:

  • 1 <= startValue, target <= 109
lightbulb

解题思路

方法一:逆向计算

我们可以采用逆向计算的方式,从 target\textit{target} 开始,如果 target\textit{target} 是奇数,那么 target=target+1\textit{target} = \textit{target} + 1,否则 target=target/2\textit{target} = \textit{target} / 2,累加操作次数,直到 targetstartValue\textit{target} \leq \textit{startValue},此时的操作次数加上 startValuetarget\textit{startValue} - \textit{target} 即为最终结果。

时间复杂度 O(logn)O(\log n),其中 nntarget\textit{target}。空间复杂度 O(1)O(1)

1
2
3
4
5
6
7
8
9
10
11
12
class Solution:
    def brokenCalc(self, startValue: int, target: int) -> int:
        ans = 0
        while startValue < target:
            if target & 1:
                target += 1
            else:
                target >>= 1
            ans += 1
        ans += startValue - target
        return ans
speed

复杂度分析

指标
时间O(\log target)
空间O(1)
psychology

面试官常问的追问

外企场景
  • question_mark

    Checks if you can apply a greedy strategy in reverse to minimize operations.

  • question_mark

    Wants validation of invariants at each step to ensure correctness.

  • question_mark

    Assesses understanding of O(log target) efficiency for large input ranges.

warning

常见陷阱

外企场景
  • error

    Trying to move forward greedily can overshoot the target and increase operations.

  • error

    Failing to handle odd targets properly when halving in reverse.

  • error

    Overcomplicating with unnecessary data structures instead of counting operations directly.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Allow an additional multiply by 3 operation and analyze how the greedy pattern changes.

  • arrow_right_alt

    Compute minimal operations for a range of targets from a fixed startValue.

  • arrow_right_alt

    Introduce negative numbers as targets and adjust the greedy invariant for decrementing.

help

常见问题

外企场景

坏了的计算器题解:贪心·invariant | LeetCode #991 中等