Re: [闲聊] 每日leetcode

楼主: sustainer123 (caster)   2024-09-17 19:38:46
※ 引述《JIWP (神楽めあ的钱包)》之铭言:
: 这题是我每日连续第300天
: 快满一年,可以不用继续写了吗
: 539. Minimum Time Difference
: 给你一个24小时制的时间清单
: 格式为"HH:MM"
: 请回传任意两个时间差的最小值
: 思路:
: 就先把时间转换成数字
: 接着排序一下
: 再来抓出差距最小的时间差
: GOLANG CODE:
: func findMinDifference(timePoints []string) int {
: n := len(timePoints)
: rec := make([]int, 0, n)
: for _, time := range timePoints {
: hours, _ := strconv.Atoi(time[0:2])
: mins, _ := strconv.Atoi(time[3:])
: rec = append(rec, hours*60+mins)
: }
: abs := func(a int) int {
: if a < 0 {
: return -a
: }
: return a
: }
: slices.Sort(rec)
: prev, res := rec[0], 100000
: for i := 1; i < n; i++ {
: diff := abs(prev - rec[i])
: if diff > 720 {
: res = min(1440-diff, res)
: } else {
: res = min(diff, res)
: }
: prev = rec[i]
: }
: diff := abs(rec[0] - rec[n-1])
: if diff > 720 {
: res = min(1440-diff, res)
: } else {
: res = min(diff, res)
: }
: return res
: }
思路:
差不多 数字拆一下 00换成24 排序 计算 因为时钟有两个方向
所以还要算原本的差跟1440-原本的差哪个小
取小的再比较
Python Code:
class Solution:
def findMinDifference(self, timePoints: List[str]) -> int:
result = float("inf")
tmp = []
for t in timePoints:
t = t.split(":")
if t[0] == "00":
t[0] = "24"
tmp.append(t)
tmp.sort()
for i in range(len(tmp)):
diff = abs((int(tmp[i][0]) - int(tmp[i-1][0])) * 60 +
int(tmp[i][1]) - int(tmp[i-1][1]))
diff = min(diff,1440-diff)
result = min(result,diff)
return result

Links booklink

Contact Us: admin [ a t ] ucptt.com