难度: Medium
Submission
运行时间: 27 ms
内存: 16.1 MB
class Solution: def nextClosestTime(self, time: str) -> str: digit = set() for t in time: if t != ":": digit.add(t) if len(digit) == 1: return time original_time = int(time[0:2]) * 60 + int(time[3: ]) hh = [] mm = [] for d1 in digit: for d2 in digit: d = d1 + d2 if int(d) < 60: mm.append(d) if int(d) < 24: hh.append(d) ans = 0 gap = float("inf") for h in hh: for m in mm: now = int(h) * 60 + int(m) if now == original_time: continue tmp_gap = (-original_time + now) % (60 * 24) if tmp_gap < gap: gap = min(gap, tmp_gap) ans = now res_h = str(ans // 60).zfill(2) res_m = str(ans % 60).zfill(2) return res_h + ":" + res_m
Explain
这个题解的思路是:先将时间字符串中出现的所有不同数字存入一个集合中。如果集合大小为1,说明所有数字都相同,直接返回原始时间。否则,将原始时间转换为分钟数。接着,用两个嵌套循环生成所有可能的小时和分钟组合,并分别存入两个列表中。最后再用两个嵌套循环遍历所有可能的时间组合,找出与原始时间差距最小的下一个最近时刻,将其转换为字符串格式返回。
时间复杂度: O(1)
空间复杂度: O(1)
class Solution: def nextClosestTime(self, time: str) -> str: # 将时间中出现的不同数字存入集合 digit = set() for t in time: if t != ":": digit.add(t) # 如果只有一种数字,直接返回原始时间 if len(digit) == 1: return time # 将原始时间转换为分钟数 original_time = int(time[0:2]) * 60 + int(time[3:]) # 存储可能的小时和分钟 hh = [] mm = [] # 生成所有可能的小时和分钟组合 for d1 in digit: for d2 in digit: d = d1 + d2 if int(d) < 60: mm.append(d) if int(d) < 24: hh.append(d) # 寻找下一个最近时刻 ans = 0 gap = float("inf") for h in hh: for m in mm: now = int(h) * 60 + int(m) if now == original_time: continue tmp_gap = (-original_time + now) % (60 * 24) if tmp_gap < gap: gap = min(gap, tmp_gap) ans = now # 将最近时刻转换为字符串格式 res_h = str(ans // 60).zfill(2) res_m = str(ans % 60).zfill(2) return res_h + ":" + res_m
Explore
在处理时间格式时,时间是以小时和分钟表示的。其中,分钟数的范围是从00到59,因此有60个可能的分钟值。这就是分钟数使用60作为上限的原因。类似地,小时数的范围是从00到23,总共24个小时,这就是小时数使用24作为上限的原因。在生成可能的时间组合时,必须确保小时和分钟的值不超过这些界限,以确保生成的时间是有效的。