将时间 T1 转换为 T2 的最小时隙
给定两个字符串T1和T2代表 24 小时格式的两个时间实例,任务是使用 1、5、15或 60 分钟之间的最小时隙数将T1转换为T2 。
24-hour times are formatted as “HH: MM”, where HH is between 00 and 23, and MM is between 00 and 59. The earliest 24-hour time is 00:00, and the latest is 23:59.
例子:
Input: T1 = “02:30”, T2 = “04:35”
Output: 3
Explanation: The time difference between them is 2 hours and 5 minutes.
Increase T1 by 60 minutes 2 times and 1 time by 5 minutes.
Input: T1 = “11:00”, T2 = “11:01”
Output: 1
Explanation: Increased the time by 1 minutes for once.
方法:这个问题可以使用基于以下思想的贪心方法来解决。
To minimize the required slots, use the ones with the highest time first and then go for the smaller ones, i.e. in the order 60, 15, 5, 1. with 60 used first and 1 used and last
按照以下步骤实现上述想法:
- 将字符串T1和T2转换为它们各自的时间并以分钟为单位存储它们(比如time1_to_min和time2_to_min )。
- 初始化一个变量来存储时隙的数量(比如操作)。
- 运行直到time1_to_min != time2_to_min
- 找出时间之间的差异(比如diff )。
- 如果差异≥ 60 然后从time2_to_min减少 60 并将操作增加 1。
- 如果diff ≥ 15 且diff < 60,则从time2_to_min递减 15 并将操作递增 1。
- 如果diff ≥ 5 且diff < 15,则从time2_to_min递减 5 并将操作递增 1。
- 否则从time2_to_min减 1 并将操作加 1。
- 返回操作,因为这是所需的最小时隙数。
下面是上述方法的实现。
C++
// C++ code to implement the approach
#include
using namespace std;
// Function for calculating the minimum
// number of operation required to
// convert time1 to time2
int convertTime(string T1, string T2)
{
// Converting strings into integer
int hour_time1 = stoi(T1.substr(0, 2));
int min_time1 = stoi(T1.substr(3, 4));
int hour_time2 = stoi(T2.substr(0, 2));
int min_time2 = stoi(T2.substr(3, 4));
// Converting time into minutes
int time1_to_min = (hour_time1 * 60) + min_time1;
int time2_to_min = (hour_time2 * 60) + min_time2;
int operations = 0;
while (time1_to_min != time2_to_min) {
int diff = time2_to_min - time1_to_min;
if (diff >= 60) {
time2_to_min -= 60;
operations++;
}
else if (diff >= 15 && diff < 60) {
time2_to_min -= 15;
operations++;
}
else if (diff >= 5 && diff < 15) {
time2_to_min -= 5;
operations++;
}
else {
time2_to_min -= 1;
operations++;
}
}
return operations;
}
// Driver code
int main()
{
// Input two strings
string T1 = "02:30";
string T2 = "04:35";
// Function call
int result = convertTime(T1, T2);
cout << " " << result << endl;
return 0;
}
3
时间复杂度: O(M) 其中 M 是时间差
辅助空间: O(1)