题目
给定一个 24 小时制(小时:分钟 "HH:MM")的时间列表,找出列表中任意两个时间的最小时间差并以分钟数表示。
示例 1:输入:timePoints = ["23:59","00:00"] 输出:1
示例 2:输入:timePoints = ["00:00","23:59","00:00"]输出:0
提示:2 <= timePoints <= 2 * 104
timePoints[i] 格式为 "HH:MM"
解题思路分析
1、排序;时间复杂度O(nlog(n)),空间复杂度O(n)
func findMinDifference(timePoints []string) int {m := make(map[int]bool)for i := 0; i < len(timePoints); i++ {value := getValue(timePoints[i])if _, ok := m[value]; ok {return 0}m[value] = true}arr := make([]int, 0)for k := range m {arr = append(arr, k)}sort.Ints(arr)res := math.MaxInt32arr = append(arr, arr[0]+1440)for i := 1; i < len(arr); i++ {if res > arr[i]-arr[i-1] {res = arr[i] - arr[i-1]}}return res}func getValue(str string) int {hour, _ := strconv.Atoi(str[:2])minute, _ := strconv.Atoi(str[3:])return hour*60 + minute}
2、排序;时间复杂度O(nlog(n)),空间复杂度O(n)
func findMinDifference(timePoints []string) int {arr := make([]int, 0)for i := 0; i < len(timePoints); i++ {value := getValue(timePoints[i])arr = append(arr, value)}sort.Ints(arr)res := math.MaxInt32arr = append(arr, arr[0]+1440)for i := 1; i < len(arr); i++ {if res > arr[i]-arr[i-1] {res = arr[i] - arr[i-1]}}return res}func getValue(str string) int {hour, _ := strconv.Atoi(str[:2])minute, _ := strconv.Atoi(str[3:])return hour*60 + minute}
总结
Medium题目,字符串转为分钟数,然后排序后计算即可