LeetCode Q 539 - 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
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.
Solution:
First sort the list. The minimum time difference can only happen between two adjacent times or between the first and last time.
Code:
public int findMinDifference(List<String> timePoints) {
Collections.sort(timePoints);
int l = 0, r = timePoints.size() - 1;
int res = change2Mins(timePoints.get(l)) + 24 * 60 - change2Mins(timePoints.get(r));
while (l <= r - 1) {
int lmins1 = change2Mins(timePoints.get(l));
int lmins2 = change2Mins(timePoints.get(l + 1));
if (lmins2 - lmins1 < res) res = lmins2 - lmins1;
l++;
}
return res;
}
private int change2Mins(String time) {
int mins = Integer.parseInt(time.substring(3, 5));
int hours = Integer.parseInt(time.substring(0, 2));
return hours * 60 + mins;
}