Python解Leetcode: 539. Minimum Time Difference

本文介绍了一种算法,用于从给定的时间列表中找到任意两个时间之间的最小差值。通过将时间转换为十进制整数并排序,再利用Python的zip函数简化代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  • 题目描述:给定一个由时间字符组成的列表,找出任意两个时间之间最小的差值。

  • 思路:
  1. 把给定的链表排序,并且在排序的同时把60进制的时间转化成十进制整数;
  2. 遍历排序的数组,求出两个相邻值之间的差值;
  3. 求出首尾两个值之间的差值。
class Solution(object):
    def findMinDifference(self, timePoints):
        """
        :type timePoints: List[str]
        :rtype: int
        """
        t = sorted(int(t[:2]) * 60 + int(t[-2:]) for t in timePoints)
        ret = 100000
        length = len(t)
        for i in range(length - 1):
            poor = t[i+1] - t[i]
            if poor < ret:
                ret = poor
        last = t[-1] - t[0] if t[-1]-t[0] <= 720 else 1440 - (t[-1]-t[0])
        ret = last if last < ret else ret
        return ret   

以上解决办法思路没问题,但是代码写出来不是很优,发现有大神写的,充分利用了Python的zip,很Pythonic,如下:

class Solution(object):
    def findMinDifference(self, timePoints):
        """
        :type timePoints: List[str]
        :rtype: int
        """
        t = sorted(int(t[:2]) * 60 + int(t[-2:]) for t in timePoints)
        t.append(t[0] + 1440)
        return min(b - a for a, b in zip(t, t[1:]))

转载于:https://www.cnblogs.com/qiaojushuang/p/7965823.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值