Skip to content

Commit

Permalink
add sol
Browse files Browse the repository at this point in the history
  • Loading branch information
ductnn committed Sep 16, 2024
1 parent 1408900 commit 41e5e47
Show file tree
Hide file tree
Showing 2 changed files with 80 additions and 0 deletions.
53 changes: 53 additions & 0 deletions leetcode/539.MinimumTimeDifference/sol.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
// https://leetcode.com/problems/minimum-time-difference/

package main

import (
"fmt"
"math"
"sort"
"strconv"
"strings"
)

func findMinDifference(timePoints []string) int {
// Convert time to minute
timeToMinutes := func(time string) int {
parts := strings.Split(time, ":")
hours, _ := strconv.Atoi(parts[0])
minutes, _ := strconv.Atoi(parts[1])

return hours*60 + minutes
}

// Sort list minute
minuteList := make([]int, len(timePoints))
for i, time := range timePoints {
minuteList[i] = timeToMinutes(time)
}
sort.Ints(minuteList)

// Caculate the difference
minDiff := math.MaxInt32
for i := 1; i < len(minuteList); i++ {
minDiff = min(minDiff, minuteList[i]-minuteList[i-1])
}

// Find the min
minDiff = min(minDiff, 24*60-minuteList[len(minuteList)-1]+minuteList[0])

return minDiff
}

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

func main() {
timePoints := []string{"23:59", "00:00"}
result := findMinDifference(timePoints)
fmt.Println(result)
}
27 changes: 27 additions & 0 deletions leetcode/539.MinimumTimeDifference/sol.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
class Solution:
def findMinDifference(self, timePoints: list[str]) -> int:
# Convert time to minutes since "00:00"
def timeToMinutes(time: str) -> int:
hours, minutes = map(int, time.split(":"))
return hours * 60 + minutes

# Convert all time points to minutes and sort them
minutes_list = sorted(timeToMinutes(time) for time in timePoints)

# Initialize minimum difference with a large number
min_diff = float('inf')

# Compare consecutive times
for i in range(1, len(minutes_list)):
min_diff = min(min_diff, minutes_list[i] - minutes_list[i - 1])

# Compare the first and last time, considering the circular nature of time
min_diff = min(min_diff, (24 * 60 - minutes_list[-1] + minutes_list[0]))

return min_diff

if __name__ == "__main__":
solution = Solution()
timePoints = ["23:59", "00:00"]
result = solution.findMinDifference(timePoints)
print(result)

0 comments on commit 41e5e47

Please sign in to comment.