题目链接:https://leetcode.com/problems/minimum-time-difference/description/
题目:
Given a list of 24-hour clock time points in "Hour:Minutes" format, find the minimum minutes difference between any two time points in the list.
Example 1:
Input: ["23:59","00:00"] Output: 1
Note:
- The number of time points in the given list is at least 2 and won't exceed 20000.
- The input time is legal and ranges from 00:00 to 23:59.
思路:
实际上对整个数组排序,然后相邻两两对比,取差值最小的返回(注意:最后一个和第一个的差值也要对比)
代码如下:
class Solution {
public:
int difference(string a0, string b0) {
int a1 = (a0[0] - '0') * 600 + (a0[1] - '0') * 60 + (a0[3] - '0') * 10 + (a0[4] - '0');
int b1 = (b0[0] - '0') * 600 + (b0[1] - '0') * 60 + (b0[3] - '0') * 10 + (b0[4] - '0');
int result = abs(a1 - b1);
return result > 1440 - result ? 1440 - result : result;
}
int findMinDifference(vector<string>& timePoints) {
sort(timePoints.begin(), timePoints.end());
int result = INT_MAX;
int len = timePoints.size();
for(int i = 0; i < len; i++ ) {
int diff = difference(timePoints[i], timePoints[(i + 1)%len]);
result = result > diff ? diff : result;
}
return result;
}
};