给定一个 24 小时制(小时:分钟)的时间列表,找出列表中任意两个时间的最小时间差并已分钟数表示。
示例 1:
输入: ["23:59","00:00"] 输出: 1
备注:
列表中时间数在 2~20000 之间。
每个时间取值在 00:00~23:59 之间。
C++
class Solution {
public:
static bool compare(string& a, string& b)
{
if(a.substr(0,2)==b.substr(0,2))
{
return a.substr(3,2) < b.substr(3,2);
}
else
{
return a.substr(0,2) < b.substr(0,2);
}
}
int findMinDifference(vector<string>& timePoints)
{
int n=timePoints.size();
sort(timePoints.begin(), timePoints.end(), compare);
int res=INT_MAX;
for(int i=1;i<n;i++)
{
int tmp=(stoi(timePoints[i].substr(0,2))-stoi(timePoints[i-1].substr(0,2)))*60+stoi(timePoints[i].substr(3,2))-stoi(timePoints[i-1].substr(3,2));
if(tmp<res)
{
res=tmp;
}
}
int tmp=(stoi(timePoints[0].substr(0,2))-stoi(timePoints[n-1].substr(0,2))+24)*60+stoi(timePoints[0].substr(3,2))-stoi(timePoints[n-1].substr(3,2));
return min(res,tmp);
}
};
python
class Solution:
def findMinDifference(self, timePoints: 'List[str]') -> 'int':
n=len(timePoints)
res=[]
for i in range(n):
res.append(int(timePoints[i][0:2])*60+int(timePoints[i][3:5]))
res.sort()
tmp=res[0]+24*60-res[n-1]
for i in range(1,n):
tmp=min(tmp,res[i]-res[i-1])
return tmp