LeetCode: Minimum Time Difference
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
思路:
这个题目的思路还是比较简单的,找到两个间隔最小的时间对,首先想到的就是排序,这个题目的一点就在于首尾的处理,比如23:59与00:00的间隔计算,这个间隔可以是23:59-00:00也可以是(24:00-23:59)+00:00,
所以对于首尾计算一下这两种计算方法的最小值就可以了。
1 int getMin(const string& s) 2 { 3 return atoi(s.substr(0, 2).c_str()) * 60 + atoi(s.substr(3, 2).c_str()); 4 } 5 int getdisabs(const string& a, const string& b) 6 { 7 return abs(getMin(a) - getMin(b)); 8 } 9 bool cmp(const string& a, const string& b) 10 { 11 return getMin(a) < getMin(b); 12 } 13 int findMinDifference(vector<string>& timePoints) 14 { 15 int size = timePoints.size(); 16 if (size <= 1) 17 return 0; 18 sort(timePoints.begin(), timePoints.end(), cmp); 19 20 int r = 0x7fffffff; 21 for (int i = 1; i < size; i++) 22 r = min(r, getdisabs(timePoints[i], timePoints[i - 1])); 23 string t = "24:00"; 24 return min(r,getdisabs(timePoints[size-1],t)+getMin(timePoints[0])); 25 }
如果你有任何疑问或新的想法,欢迎在下方评论。