问题描述:
Given a list of 24-hour clock time points in "Hour:Minutes" format, find the minimum minutes difference between any two time points in the list.
示例:
Input: ["23:59","00:00"] Output: 1
Note:
- The number of time points in the given list is at least 2 and won't exceed 20000.
- The input time is legal and ranges from 00:00 to 23:59.
问题分析:
将时间转换为整数值,然后升序排序,计算相邻数值之间的差值(最后一个和第一个算做系相邻元素),最小的差值即为答案。
过程详见代码:
class Solution {
public:
int findMinDifference(vector<string>& timePoints) {
sort(timePoints.begin(), timePoints.end());
int mini = INT_MAX;
int hour1 = stoi((timePoints[0]).substr(0, 2)),hour2;
int minute1 = stoi((timePoints[0]).substr(3, 2)),minute2;
for (int i = 1; i < timePoints.size(); i++)
{
hour2 = stoi((timePoints[i]).substr(0, 2));
minute2 = stoi((timePoints[i]).substr(3, 2));
mini = min(mini, (hour2 - hour1) * 60 + (minute2 - minute1));
hour1 = hour2;
minute1 = minute2;
}
int m = (23 - hour1) * 60 + (60 - minute1) ;
hour1 = stoi((timePoints[0]).substr(0, 2));
minute1 = stoi((timePoints[0]).substr(3, 2));
m = m + hour1 * 60 + minute1;
mini = min(mini, m);
return mini;
}
};