问题:
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.
解决:
① 求两个时间点之间的最小差值。给数组排序,这样时间点小的就在前面了,然后我们分别把小时和分钟提取出来,计算差值,注意唯一的特殊情况就是第一个和末尾的时间点进行比较,第一个时间点需要加上24小时再做差值。O(nlgn)
class Solution { //31ms
public int findMinDifference(List<String> timePoints) {
int min = Integer.MAX_VALUE;
int len = timePoints.size();
int diff = 0;
String[] times = new String[len];
for (int i = 0;i < len;i ++){
times[i] = timePoints.get(i);
}
Arrays.sort(times);
for (int i = 0;i < len;i ++){
String t1 = times[i];
String t2 = times[(i + 1) % len];
int h1 = (t1.charAt(0) - '0') * 10 + t1.charAt(1) - '0';
int m1 = (t1.charAt(3) - '0') * 10 + t1.charAt(4) - '0';
int h2 = (t2.charAt(0) - '0') * 10 + t2.charAt(1) - '0';
int m2 = (t2.charAt(3) - '0') * 10 + t2.charAt(4) - '0';
diff = (h2 - h1) * 60 + (m2 - m1);
if (i == len - 1) diff += 24 * 60;
min = Math.min(min,diff);
}
return min;
}
}
② 由于时间点并不是无穷多个,而是只有1440个,所以我们建立一个大小为1440的数组来标记某个时间点是否出现过,如果之前已经出现过,说明有两个相同的时间点,直接返回0即可;若没有,将当前时间点标记为出现过。我们还需要一些辅助变量,pre表示之前遍历到的时间点,first表示按顺序排的第一个时间点,last表示按顺序排的最后一个时间点,然后我们再遍历这个mask数组,如果当前时间点出现过,再看如果first不为初始值的话,说明pre已经被更新过了,我们用当前时间点减去pre来更新结果res,然后再分别更新first,last,和pre即可。O(n)
class Solution { //41ms
public int findMinDifference(List<String> timePoints) {
int min = Integer.MAX_VALUE;
int len = timePoints.size();
int diff = 0;
String[] times = new String[len];
for (int i = 0;i < len;i ++){
times[i] = timePoints.get(i);
}
Arrays.sort(times);
for (int i = 0;i < len;i ++){
String t1 = times[i];
String t2 = times[(i + 1) % len];
int h1 = (t1.charAt(0) - '0') * 10 + t1.charAt(1) - '0';
int m1 = (t1.charAt(3) - '0') * 10 + t1.charAt(4) - '0';
int h2 = (t2.charAt(0) - '0') * 10 + t2.charAt(1) - '0';
int m2 = (t2.charAt(3) - '0') * 10 + t2.charAt(4) - '0';
diff = (h2 - h1) * 60 + (m2 - m1);
if (i == len - 1) diff += 24 * 60;
min = Math.min(min,diff);
}
return min;
}
}