※ 引述《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