Question
Given a list of 24-hour clock time points in "Hour:Minutes" format, find the minimum minutes difference between any two time points in the list.
Example 1:
Note:
Solution
Naive
- from datetime import datetime
- class Solution:
- def findMinDifference(self, timePoints: List[str]) -> int:
- ts_list = list(map(lambda t: int(t[0])*60 + int(t[1]) if t[0]!='00' or t[1]!='00' else 60*24, map(lambda s:s.split(':'), timePoints)))
- # max min diff = 720 happens in 00:00 - 12:00
- # 00:00 - 12:01 with diff
- # min( 00:00 - 12:01 = 721, 12:01 - 24:00 = 719) = 719
- def time_diff(t1, t2):
- td = abs(t1 - t2)
- return td if td < 12 * 60 else 1440 - td
- ts_list.sort()
- min_td = float('inf')
- ts_len = len(ts_list)
- for i in range(0, ts_len):
- td = time_diff(ts_list[i], ts_list[i-1])
- if td < min_td:
- min_td = td
- return min_td
Discussion_1 (link)
- class Solution:
- def findMinDifference(self, timePoints: List[str]) -> int:
- minutes = sorted(list(map(lambda x: int(x[:2]) * 60 + int(x[3:]), timePoints)))
- return min((y - x) % (24 * 60) for x, y in zip(minutes, minutes[1:] + minutes[:1]))
Supplement
* Python 文章收集 - How To Convert Timestamp To Date and Time in Python
* FAQ - Convert string date to timestamp in Python
* Python timestamp to datetime and vice-versa
沒有留言:
張貼留言