LeetCode 题解工作台
最小时间差
给定一个 24 小时制(小时:分钟 "HH:MM" )的时间列表,找出列表中任意两个时间的最小时间差并以分钟数表示。 示例 1: 输入: timePoints = ["23:59","00:00"] 输出: 1 示例 2: 输入: timePoints = ["00:00","23:59","00:…
4
题型
7
代码语言
3
相关题
当前训练重点
中等 · 数组·数学
答案摘要
我们注意到,时间点最多只有 $24 \times 60 = 1440$ 个,因此,当 长度超过 ,说明有重复的时间点,提前返回 。 接下来,我们首先遍历时间列表,将其转换为“分钟制”列表 ,比如,对于时间点 `13:14`,将其转换为 $13 \times 60 + 14$。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·数学 题型思路
题目描述
给定一个 24 小时制(小时:分钟 "HH:MM")的时间列表,找出列表中任意两个时间的最小时间差并以分钟数表示。
示例 1:
输入:timePoints = ["23:59","00:00"] 输出:1
示例 2:
输入:timePoints = ["00:00","23:59","00:00"] 输出:0
提示:
2 <= timePoints.length <= 2 * 104timePoints[i]格式为 "HH:MM"
解题思路
方法一:排序
我们注意到,时间点最多只有 个,因此,当 长度超过 ,说明有重复的时间点,提前返回 。
接下来,我们首先遍历时间列表,将其转换为“分钟制”列表 ,比如,对于时间点 13:14,将其转换为 。
接着将“分钟制”列表按升序排列,然后将此列表的最小时间 加上 追加至列表尾部,用于处理最大值、最小值的差值这种特殊情况。
最后遍历“分钟制”列表,找出相邻两个时间的最小值即可。
时间复杂度 ,空间复杂度 。其中 为时间点个数。
class Solution:
def findMinDifference(self, timePoints: List[str]) -> int:
if len(timePoints) > 1440:
return 0
nums = sorted(int(x[:2]) * 60 + int(x[3:]) for x in timePoints)
nums.append(nums[0] + 1440)
return min(b - a for a, b in pairwise(nums))
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(N) for converting and sorting if bucket counting is used, otherwise O(N log N) with standard sort. Space complexity is O(1) aside from the array of minutes since in-place computations are possible. |
| 空间 | O(1) |
面试官常问的追问
外企场景- question_mark
Asks about handling duplicates and zero-minute differences.
- question_mark
Checks awareness of circular time calculation and modulo logic.
- question_mark
Tests for edge cases like adjacent midnight values.
常见陷阱
外企场景- error
Forgetting the wrap-around from 23:59 to 00:00 and missing minimal differences.
- error
Incorrectly comparing string times instead of numeric minutes.
- error
Not handling duplicate times which can produce zero difference.
进阶变体
外企场景- arrow_right_alt
Compute maximum time difference instead of minimum.
- arrow_right_alt
Allow times with seconds and compute minimal difference including seconds.
- arrow_right_alt
Find k smallest differences among all time points.