- 题目描述:给定一个由时间字符组成的列表,找出任意两个时间之间最小的差值。
- 思路:
- 把给定的链表排序,并且在排序的同时把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:]))
时间: 2024-10-09 12:38:45