给定一个 24 小时制(小时:分钟 “HH:MM”)的时间列表,找出列表中任意两个时间的最小时间差并以分钟数表示。
示例 1:
输入:timePoints = [“23:59”,“00:00”]
输出:1
示例 2:
输入:timePoints = [“00:00”,“23:59”,“00:00”]
输出:0
提示:
2 <= timePoints.length <= 2 * 104
timePoints[i] 格式为 “HH:MM”
class Solution {
public:int findMinDifference(vector<string>& timePoints) {vector<int> time;for(auto s : timePoints) {int h, m;if(s[0] == '0') h = s[1] - '0';else h = (s[0] - '0') * 10 + (s[1] - '0');if(s[3] == '0') m = s[4] - '0';else m = (s[3] - '0') * 10 + (s[4] - '0');time.push_back(h * 60 + m);}sort(time.begin(), time.end());int res = INT_MAX;for(int i = 0; i < time.size() - 1; i ++ ) {res = min(res, time[i + 1] - time[i]);}res = min(res, (24 * 60) - time[time.size() - 1] + time[0]);return res;}
};
更简便的写法:
class Solution {
public:int findMinDifference(vector<string>& timePoints) {int res = INT_MAX;vector<int> q;for(auto t : timePoints) {int h, m;sscanf(t.c_str(), "%d:%d", &h, &m);q.push_back(h * 60 + m);}sort(q.begin(), q.end());for(int i = 1; i < q.size(); i ++ ) res = min(res, q[i] - q[i - 1]);res = min(res, 24 * 60 - q.back() + q[0]);return res;}
};