📅  最后修改于: 2023-12-03 14:53:56.374000             🧑  作者: Mango
给定n个时间,每个时间由小时(0-23)和分钟(0-59)表示。请编写一个函数,查找可以在范围[m, n]内找到的最长时间(以分钟为单位),其中0 <= m <= n <= 1440,并返回该时间。
例如,如果给定以下时间:
["12:12", "13:13", "14:14", "15:15"]
则函数应该返回3,因为可以选取任意两个时间差异为3分钟。
将每个时间都转换成分钟,用两个指针i和j遍历这个数组,计算时间差,并通过判断时间差是否在[m,n]内来决定i和j是否需要往前移动。该算法时间复杂度为O(nlogn)。
def find_max_time(times, m, n):
time_in_minute = []
for time in times:
hour, minute = time.split(':')
time_in_minute.append(int(hour) * 60 + int(minute))
time_in_minute.sort()
i, j = 0, 1
max_time = 0
while i < len(time_in_minute) and j < len(time_in_minute):
diff = time_in_minute[j] - time_in_minute[i]
if m <= diff <= n:
max_time = max(max_time, diff)
j += 1
elif diff < m:
j += 1
else:
i += 1
return max_time
times = ["12:12", "13:13", "14:14", "15:15"]
m = 3
n = 5
assert find_max_time(times, m, n) == 3