Skip to content

Latest commit

 

History

History

2224.Minimum Number of Operations to Convert Time

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 
 
 
 
 
 
 
 
 

English Version

题目描述

给你两个字符串 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

解法

方法一:贪心

Python3

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

Java

class Solution {
    public int convertTime(String current, String correct) {
        int a = Integer.parseInt(current.substring(0, 2)) * 60 + Integer.parseInt(current.substring(3));
        int b = Integer.parseInt(correct.substring(0, 2)) * 60 + Integer.parseInt(correct.substring(3));
        int ans = 0, d = b - a;
        for (int i : Arrays.asList(60, 15, 5, 1)) {
            ans += d / i;
            d %= i;
        }
        return ans;
    }
}

C++

class Solution {
public:
    int convertTime(string current, string correct) {
        int a = stoi(current.substr(0, 2)) * 60 + stoi(current.substr(3, 2));
        int b = stoi(correct.substr(0, 2)) * 60 + stoi(correct.substr(3, 2));
        int ans = 0, d = b - a;
        vector<int> inc = {60, 15, 5, 1};
        for (int i : inc)
        {
            ans += d / i;
            d %= i;
        }
        return ans;
    }
};

Go

func convertTime(current string, correct string) int {
    parse := func(s string) int {
        h := int(s[0] - '0') * 10 + int(s[1] - '0')
        m := int(s[3] - '0') * 10 + int(s[4] - '0')
        return h * 60 + m
    }
    a, b := parse(current), parse(correct)
    ans, d := 0, b - a
    for _, i := range []int{60, 15, 5, 1} {
        ans += d / i
        d %= i
    }
    return ans
}

TypeScript

...