目录

0539:最小时间差(★)

力扣第 539 题

题目

给定一个 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"

相似问题:

分析

#1

  • 统一转为分钟数,求相邻最小差值即可
  • 注意相当于循环数组,考虑首减去尾的情况
1
2
3
4
5
6
7
8
class Solution:
    def findMinDifference(self, timePoints: List[str]) -> int:
        A = []
        for t in timePoints:
            h,m = map(int,t.split(':'))
            A.append(h*60+m)
        A.sort()
        return min(min(b-a for a,b in pairwise(A)),A[0]+1440-A[-1])

69 ms

#2

分钟数最多 1440 种,因此 n>1440 时必然有重复,返回 0 即可。

解答

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Solution:
    def findMinDifference(self, timePoints: List[str]) -> int:
        if len(timePoints)>1440:
            return 0
        A = []
        for t in timePoints:
            h,m = map(int,t.split(':'))
            A.append(h*60+m)
        A.sort()
        return min(min(b-a for a,b in pairwise(A)),A[0]+1440-A[-1])

32 ms