- 最小时间差
给定一个 24 小时制(小时:分钟 “HH:MM”)的时间列表,找出列表中任意两个时间的最小时间差并以分钟数表示。
示例 1:
输入:timePoints = [“23:59”,“00:00”]
输出:1
示例 2:
输入:timePoints = [“00:00”,“23:59”,“00:00”]
输出:0
提示:
2 <= timePoints <= 2 * 104
timePoints[i] 格式为 "HH:MM"
题解
模拟+排序,因为时间存在循环,所以排序后和前面以及后面的时间做差比较。
AC代码
class Solution {
public:
vector<int>q;
int mod=24*60;
int findMinDifference(vector<string>& timePoints)
{
for(int i=0;i<timePoints.size();i++)
{
q.push_back(((timePoints[i][0]-'0')*10+(timePoints[i][1]-'0'))*60+(timePoints[i][3]-'0')*10+(timePoints[i][4]-'0'));
}
int mi=1e9;
sort(q.begin(),q.end());
for(int i=0;i<q.size();i++)
{
if(i==0)
{
mi=min(mi,(q[i+1]+mod-q[i])%mod);
mi=min(mi,(q[i]+mod-q[i+1])%mod);
mi=min(mi,(q[q.size()-1]+mod-q[i])%mod);
mi=min(mi,(q[i]+mod-q[q.size()-1])%mod);
}
else if(i==q.size()-1)
{
mi=min(mi,(q[i-1]+mod-q[i])%mod);
mi=min(mi,(q[i]+mod-q[i-1])%mod);
mi=min(mi,(q[0]+mod-q[i])%mod);
mi=min(mi,(q[i]+mod-q[0])%mod);
}
else
{
mi=min(mi,(q[i-1]+mod-q[i])%mod);
mi=min(mi,(q[i]+mod-q[i-1])%mod);
mi=min(mi,(q[i+1]+mod-q[i])%mod);
mi=min(mi,(q[i]+mod-q[i+1])%mod);
}
}
return mi;
}
};