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.
Solution
给一个string的list,找到这个list中表示的时间中的任意两个时间的最小差值,可能跨天。
We use a Integer list to store the value of coverted time from String to 1440(because a day has 1440 minutes). Then sort the list from small to big. Calculate the minimum difference, and a corner case, from time[0] to tomorrow’s time[time.size() - 1]. Return the smaller one.
Code
class Solution {
public int findMinDifference(List<String> timePoints) {
int min = Integer.MAX_VALUE;
List<Integer> time = new ArrayList<>();
for (int i = 0; i < timePoints.size(); i++){
int hour = Integer.valueOf(timePoints.get(i).substring(0,2));
int minute = Integer.valueOf(timePoints.get(i).substring(3,5));
time.add(hour * 60 + minute);
}
Collections.sort(time, (Integer a, Integer b) -> a - b);
for (int i = 1; i < time.size(); i++){
min = Math.min(min, time.get(i) - time.get(i - 1));
}
int cornerCase = time.get(0) + (1440 - time.get(time.size() - 1));
return Math.min(cornerCase, min);
}
}
Time Complexity: O(n)
Space Complexity: O(n)
Review
We could also use Bucket sort, using a boolean int[] with size 1440 to document wether a time is showed in timepoints list. Then iteratively traverse the bucket, find minimum difference and calculate corner case.