文章目录
题目
标题和出处
标题:最小时间差
出处:539. 最小时间差
难度
3 级
题目描述
要求
给定一个 24 \texttt{24} 24 小时制的时间列表,时间以 "HH:MM" \texttt{"HH:MM"} "HH:MM" 的形式表示,返回列表中任意两个时间的最小时间差的分钟数表示。
示例
示例 1:
输入: timePoints = ["23:59","00:00"] \texttt{timePoints = ["23:59","00:00"]} timePoints = ["23:59","00:00"]
输出: 1 \texttt{1} 1
示例 2:
输入: timePoints = ["00:00","23:59","00:00"] \texttt{timePoints = ["00:00","23:59","00:00"]} timePoints = ["00:00","23:59","00:00"]
输出: 0 \texttt{0} 0
数据范围
- 2 ≤ timePoints.length ≤ 2 × 10 4 \texttt{2} \le \texttt{timePoints.length} \le \texttt{2} \times \texttt{10}^\texttt{4} 2≤timePoints.length≤2×104
- timePoints[i] \texttt{timePoints[i]} timePoints[i] 格式为 "HH:MM" \texttt{"HH:MM"} "HH:MM"
解法
思路和算法
首先将时间列表中的每个时间都转换成分钟数表示,得到分钟数组,则分钟数组的每个元素都在范围 [ 0 , 1439 ] [0, 1439] [0,1439] 内。
将分钟数组排序之后,最小时间差一定是数组中的两个相邻时间之差,或者数组的首元素与末元素之差加上 1440 1440 1440(一天的分钟数是 1440 1440 1440)。遍历排序后的分钟数组中的每一对相邻元素(包括首元素与末元素)计算时间差,即可得到最小时间差。
代码
java
class Solution {
public int findMinDifference(List<String> timePoints) {
int length = timePoints.size();
int[] timeArr = new int[length];
for (int i = 0; i < length; i++) {
String timePoint = timePoints.get(i);
int hour = Integer.parseInt(timePoint.substring(0, 2));
int minute = Integer.parseInt(timePoint.substring(3));
timeArr[i] = hour * 60 + minute;
}
Arrays.sort(timeArr);
int minDifference = timeArr[0] - timeArr[length - 1] + 1440;
for (int i = 1; i < length; i++) {
int difference = timeArr[i] - timeArr[i - 1];
minDifference = Math.min(minDifference, difference);
}
return minDifference;
}
}
复杂度分析
-
时间复杂度: O ( n log n ) O(n \log n) O(nlogn),其中 n n n 是时间列表 timePoints \textit{timePoints} timePoints 的长度。需要创建长度为 n n n 的分钟数组并排序,排序需要 O ( n log n ) O(n \log n) O(nlogn) 的时间,排序后遍历数组需要 O ( n ) O(n) O(n) 的时间,因此时间复杂度是 O ( n log n ) O(n \log n) O(nlogn)。
-
空间复杂度: O ( n ) O(n) O(n),其中 n n n 是时间列表 timePoints \textit{timePoints} timePoints 的长度。需要创建长度为 n n n 的分钟数组并排序,数组需要 O ( n ) O(n) O(n) 的空间,排序需要 O ( log n ) O(\log n) O(logn) 的递归调用栈空间,因此空间复杂度是 O ( n ) O(n) O(n)。