LeetCode 题解工作台

最小时间差

给定一个 24 小时制(小时:分钟 "HH:MM" )的时间列表,找出列表中任意两个时间的最小时间差并以分钟数表示。 示例 1: 输入: timePoints = ["23:59","00:00"] 输出: 1 示例 2: 输入: timePoints = ["00:00","23:59","00:…

category

4

题型

code_blocks

7

代码语言

hub

3

相关题

当前训练重点

中等 · 数组·数学

bolt

答案摘要

我们注意到,时间点最多只有 $24 \times 60 = 1440$ 个,因此,当 长度超过 ,说明有重复的时间点,提前返回 。 接下来,我们首先遍历时间列表,将其转换为“分钟制”列表 ,比如,对于时间点 `13:14`,将其转换为 $13 \times 60 + 14$。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数组·数学 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给定一个 24 小时制(小时:分钟 "HH:MM")的时间列表,找出列表中任意两个时间的最小时间差并以分钟数表示。

 

示例 1:

输入:timePoints = ["23:59","00:00"]
输出:1

示例 2:

输入:timePoints = ["00:00","23:59","00:00"]
输出:0

 

提示:

  • 2 <= timePoints.length <= 2 * 104
  • timePoints[i] 格式为 "HH:MM"
lightbulb

解题思路

方法一:排序

我们注意到,时间点最多只有 24×60=144024 \times 60 = 1440 个,因此,当 timePointstimePoints 长度超过 14401440,说明有重复的时间点,提前返回 00

接下来,我们首先遍历时间列表,将其转换为“分钟制”列表 numsnums,比如,对于时间点 13:14,将其转换为 13×60+1413 \times 60 + 14

接着将“分钟制”列表按升序排列,然后将此列表的最小时间 nums[0]nums[0] 加上 14401440 追加至列表尾部,用于处理最大值、最小值的差值这种特殊情况。

最后遍历“分钟制”列表,找出相邻两个时间的最小值即可。

时间复杂度 O(n×logn)O(n \times \log n),空间复杂度 O(n)O(n)。其中 nn 为时间点个数。

1
2
3
4
5
6
7
8
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))
speed

复杂度分析

指标
时间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)
psychology

面试官常问的追问

外企场景
  • 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.

warning

常见陷阱

外企场景
  • 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.

swap_horiz

进阶变体

外企场景
  • 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.

help

常见问题

外企场景

最小时间差题解:数组·数学 | LeetCode #539 中等