题目链接:https://leetcode-cn.com/problems/minimum-time-difference/
题目描述
给定一个 24 小时制(小时:分钟)的时间列表,找出列表中任意两个时间的最小时间差并已分钟数表示。
示例 1:
输入: ["23:59","00:00"]
输出: 1
备注:
- 列表中时间数在 2~20000 之间。
- 每个时间取值在 00:00~23:59 之间。
思路
class Solution {
public:
int findMinDifference(vector<string>& timePoints) {
sort(timePoints.begin(), timePoints.end());
int len = timePoints.size();
if(len < 1)
return 0;
auto minTime = getTimeAbs(timePoints[0], timePoints.back());// 最早和最晚的时间之差
for(int i = 1; i < timePoints.size(); ++ i){
minTime = min(minTime, getTimeAbs(timePoints[i], timePoints[i-1]));
}
return minTime;
}
private:
int str2time(string &s){
return ((s[0] - '0') * 10 + s[1] - '0') * 60 + (s[3] - '0') * 10 + (s[4] - '0') * 1; // 转化为分钟
}
int getTimeAbs(string &s1, string&s2){
auto t1 = str2time(s1);
auto t2 = str2time(s2);
auto t = abs(t1 - t2);
return min(t, 24 * 60 - t);
}
};