LeetCode 题解工作台

转化时间需要的最少操作数

给你两个字符串 current 和 correct ,表示两个 24 小时制时间 。 24 小时制时间 按 "HH:MM" 进行格式化,其中 HH 在 00 和 23 之间,而 MM 在 00 和 59 之间。最早的 24 小时制时间为 00:00 ,最晚的是 23:59 。 在一步操作中,你可以将…

category

2

题型

code_blocks

4

代码语言

hub

3

相关题

当前训练重点

简单 · 贪心·invariant

bolt

答案摘要

class Solution: def convertTime(self, current: str, correct: str) -> int:

Interview AiBox logo

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

试试 AiBox 面试助手arrow_forward
description

题目描述

给你两个字符串 currentcorrect ,表示两个 24 小时制时间

24 小时制时间"HH:MM" 进行格式化,其中 HH0023 之间,而 MM0059 之间。最早的 24 小时制时间为 00:00 ,最晚的是 23:59

在一步操作中,你可以将 current 这个时间增加 151560 分钟。你可以执行这一操作 任意 次数。

返回将 current 转化为 correct 需要的 最少操作数

 

示例 1:

输入:current = "02:30", correct = "04:35"
输出:3
解释:
可以按下述 3 步操作将 current 转换为 correct :
- 为 current 加 60 分钟,current 变为 "03:30" 。
- 为 current 加 60 分钟,current 变为 "04:30" 。 
- 为 current 加 5 分钟,current 变为 "04:35" 。
可以证明,无法用少于 3 步操作将 current 转化为 correct 。

示例 2:

输入:current = "11:00", correct = "11:01"
输出:1
解释:只需要为 current 加一分钟,所以最小操作数是 1 。

 

提示:

  • currentcorrect 都符合 "HH:MM" 格式
  • current <= correct
lightbulb

解题思路

方法一:贪心

1
2
3
4
5
6
7
8
9
10
class Solution:
    def convertTime(self, current: str, correct: str) -> int:
        a = int(current[:2]) * 60 + int(current[3:])
        b = int(correct[:2]) * 60 + int(correct[3:])
        ans, d = 0, b - a
        for i in [60, 15, 5, 1]:
            ans += d // i
            d %= i
        return ans
speed

复杂度分析

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

面试官常问的追问

外企场景
  • question_mark

    Can the candidate identify the correct greedy choice for minimizing operations?

  • question_mark

    Does the candidate understand how to convert times to a simpler representation (minutes)?

  • question_mark

    Is the candidate able to effectively implement a greedy strategy?

warning

常见陷阱

外企场景
  • error

    Failing to convert times to minutes, which complicates the difference calculation.

  • error

    Not choosing the largest increment first, which leads to a higher number of operations.

  • error

    Misunderstanding the constraints, particularly the ordering of the current and correct times.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    What if you were allowed to decrease the current time instead of only increasing it?

  • arrow_right_alt

    What if you could use different increments for each operation (e.g., 1, 2, 3, 4 minutes)?

  • arrow_right_alt

    What if the times were provided in a different format, such as 12-hour time?

help

常见问题

外企场景

转化时间需要的最少操作数题解:贪心·invariant | LeetCode #2224 简单