539. Minimum Time Difference

Medium

Given a list of 24-hour clock time points in "HH:MM" format, return the minimum minutes difference between any two time-points in the list.

Example 1:

Input: timePoints = ["23:59","00:00"]
Output: 1

Example 2:

Input: timePoints = ["00:00","23:59","00:00"]
Output: 0

Constraints:

  • 2 <= timePoints.length <= 2 * 10^4

  • timePoints[i] is in the format "HH:MM".

解鑌

Runtime: 3 ms, faster than 100%

Memory Usage: 4.2 MB, less than 97.22%

func findMinDifference(timePoints []string) int {
    sort.Slice(timePoints, func(i int, j int) bool { // 從00:00~23:59 ζŽ’εΊ
        if timePoints[i][0] == timePoints[j][0] && timePoints[i][1] == timePoints[j][1] {
            if timePoints[i][3] == timePoints[j][3] {
                return timePoints[i][4] < timePoints[j][4]
            }

            return timePoints[i][3] < timePoints[j][3]
        }

        if timePoints[i][0] == timePoints[j][0] {
            return timePoints[i][1] < timePoints[j][1]
        }

        return timePoints[i][0] < timePoints[j][0]
    })

    ans := 100000000000

    for i:=1; i<len(timePoints); i++ {
        ans = min(ans, timeToMinutes(timePoints[i]) - timeToMinutes(timePoints[i - 1]))
    }
    
    // ζœ€ε€§ηš„ζ™‚ι–“θˆ‡ζœ€ε°ηš„ζ™‚ι–“δΉ‹ι–“ιš”
    ans = min(ans, 1440 - timeToMinutes(timePoints[len(timePoints) - 1]) + timeToMinutes(timePoints[0])) 

    return ans
}

func timeToMinutes(s string) int { // θ½‰ζ›η‚Ίεˆ†ι˜
    month, err := strconv.Atoi(s[:2]) //month
    if err != nil {
        fmt.Println(err)
    }

    day, err1 := strconv.Atoi(s[3:]) //day
    if err1 != nil {
        fmt.Println(err)
    }

    return month * 60 + day
}

func min(a, b int) int {
    if a < b { return a }
    return b
}

Last updated