1.题目基本信息
1.1.题目描述
常见的微波炉可以设置加热时间,且加热时间满足以下条件:
-
至少为 1 秒钟。
-
至多为 99 分 99 秒。
你可以 最多 输入 4 个数字 来设置加热时间。如果你输入的位数不足 4 位,微波炉会自动加 前缀 0 来补足 4 位。微波炉会将设置好的四位数中,前 两位当作分钟数,后 两位当作秒数。它们所表示的总时间就是加热时间。比方说:
-
你输入 9 5 4 (三个数字),被自动补足为 0954 ,并表示 9 分 54 秒。
-
你输入 0 0 0 8 (四个数字),表示 0 分 8 秒。
-
你输入 8 0 9 0 ,表示 80 分 90 秒。
-
你输入 8 1 3 0 ,表示 81 分 30 秒。
给你整数 startAt ,moveCost ,pushCost 和 targetSeconds 。一开始,你的手指在数字 startAt 处。将手指移到 任何其他数字 ,需要花费 moveCost 的单位代价。每 输入你手指所在位置的数字一次,需要花费 pushCost 的单位代价。
要设置 targetSeconds 秒的加热时间,可能会有多种设置方法。你想要知道这些方法中,总代价最小为多少。
请你能返回设置 targetSeconds 秒钟加热时间需要花费的最少代价。
请记住,虽然微波炉的秒数最多可以设置到 99 秒,但一分钟等于 60 秒。
1.2.题目地址
https://leetcode.cn/problems/minimum-cost-to-set-cooking-time/description/
2.解题方法
2.1.解题思路
模拟+贪心
2.2.解题步骤
第一步,假如时间的前两个数为mm,后两个数为ss,构建函数cost计算在此情况下的最少代价
-
1.1.构建维护变量。index维护遍历的指针位置,从mm和ss的四个字符中第一个非0的字符位置开始;prev维护前一个输入的字符,初始化为startAt
-
1.2.从index位置开始枚举四个数字,模拟移动
-
1.2.1.如果当前数字和前一个数字不同,即移动到不同的数字位置,需要付出moveCost代价
-
1.2.2.输入需要的代价
-
第二步,ss<60和ss>=60两种情况下,调用cost函数,计算两种情况下的最少代价,并返回
3.解题代码
python代码
class Solution:
def minCostSetTime(self, startAt: int, moveCost: int, pushCost: int, targetSeconds: int) -> int:
# 思路:模拟+贪心
# 第一步,假如时间的前两个数为mm,后两个数为ss,构建函数cost计算在此情况下的最少代价
def cost(mm:int, ss:int) -> int:
if not (0 <= mm < 100 and 0 <= ss < 100):
return inf
# 1.1.构建维护变量。index维护遍历的指针位置,从mm和ss的四个字符中第一个非0的字符位置开始;prev维护前一个输入的字符,初始化为startAt
digits = [mm // 10, mm % 10, ss // 10, ss % 10]
index = 0
while index < 4 and digits[index] == 0:
index += 1
ans = 0
prev = startAt
# 1.2.从index位置开始枚举四个数字,模拟移动
while index < 4:
d = digits[index]
# 1.2.1.如果当前数字和前一个数字不同,即移动到不同的数字位置,需要付出moveCost代价
if prev != d:
ans += moveCost
prev = d
# 1.2.2.输入需要的代价
ans += pushCost
index += 1
return ans
# 第二步,ss<60和ss>=60两种情况下,调用cost函数,计算两种情况下的最少代价,并返回
s, m = targetSeconds // 60, targetSeconds % 60
return min(cost(s, m), cost(s - 1, m + 60))
4.执行结果










