Python解Leetcode: 539. Minimum Time Difference
Posted 潇湘旧友
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python解Leetcode: 539. Minimum Time Difference相关的知识,希望对你有一定的参考价值。
题目描述:给定一个由时间字符组成的列表,找出任意两个时间之间最小的差值。
- 思路:
- 把给定的链表排序,并且在排序的同时把60进制的时间转化成十进制整数;
- 遍历排序的数组,求出两个相邻值之间的差值;
- 求出首尾两个值之间的差值。
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:]))
以上是关于Python解Leetcode: 539. Minimum Time Difference的主要内容,如果未能解决你的问题,请参考以下文章
Python 解LeetCode:33. Search in Rotated Sorted Array
leetcode-539-Minimum Time Difference
leetcode--539. Minimum Time Difference