[Google] LeetCode 539 Minimum Time Difference
Given a list of 24-hour clock time points in "HH:MM
" format, return the minimum minutes difference between any two time-points in the list.
Solution
这里用到的第一个是 \(stoi\) 函数,将字符串转换成数字。其次为了求最短的时间差,注意的一点是正向和反向:
\[\min(df, 24\cdot 60-df)
\]
最后一个细节就是第一个和最后一个的时间差,因为时间是循环的,所以在 \(sort\) 以后,要把第一个时间 \(push\_back\) 进去
点击查看代码
class Solution {
private:
int dif(string t, string s){
int ht = stoi(t.substr(0,2));
int hs = stoi(s.substr(0,2));
int mt = stoi(t.substr(3,2));
int ms = stoi(s.substr(3,2));
int df = abs(60*(ht-hs)+mt-ms);
return min(df, 1440-df);
}
public:
int findMinDifference(vector<string>& timePoints) {
int n = timePoints.size();
int ans = INT_MAX;
sort(timePoints.begin(), timePoints.end());
timePoints.push_back(timePoints[0]);
for(int i=1;i<=n;i++){
ans=min(ans, dif(timePoints[i], timePoints[i-1]));
}
return ans;
}
};