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.
求数组中,两点之间时钟间隔最小值。
方法一:先将时间表达式转化为分钟整数,排序,依次判断相邻两点的分钟间隔,注意跨零点的情况
方法二:因为时间表达式转化为分钟后,整数最大值为23*60+59,该数值不是很大,因此可以采用桶排序,程序如下所示:
class Solution {
private final int MAX_LEN = 24*60;
public int findMinDifference(List<String> timePoints) {
int len = timePoints.size();
boolean[] bucket = new boolean[MAX_LEN];
int hour = 0, minute = 0, cur = 0;
int left = MAX_LEN, right = 0;
for (String val : timePoints){
hour = Integer.parseInt(val.substring(0, 2));
minute = Integer.parseInt(val.substring(val.length() - 2, val.length()));
cur = hour * 60 + minute;
if (bucket[cur]){
return 0;
}
bucket[cur] = true;
left = Math.min(left, cur);
right = Math.max(right, cur);
}
int res = MAX_LEN;
Integer pre = null;
while (left <= right){
while (!bucket[left]){
left ++;
}
if (pre != null){
res = Math.min(res, Math.min(left - pre, pre + MAX_LEN - right));
}
pre = left;
left ++;
}
return res;
}
}