Minimum Time Difference
Description
Given a list of 24-hour clock time points in "Hour:Minutes" format, find the minimum minutes difference between any two time points in the list.
Example 1:
Input: ["23:59","00:00"] Output: 1
Note:
- The number of time points in the given list is at least 2 and won't exceed 20000.
- The input time is legal and ranges from 00:00 to 23:59.
Solution(javascript)
// O(nlog(n)) 也可以用桶排(O(n)) 这题注意时间的比较,每个时间其实是两个时间点
const findMinDifference = function (timePoints = []) {
const getTime = (str = '') => str.split(':').map(time => parseInt(time, 10))
const times = timePoints.map((time) => {
const [hour1, minute1] = getTime(time)
return hour1 * 60 + minute1
})
const sorted = []
let duplicate = false
times.forEach((time) => {
if (sorted[time] !== undefined || sorted[time + 24 * 60] !== undefined) {
duplicate = true
}
sorted[time] = time
sorted[time + 24 * 60] = time + 24 * 60
})
if (duplicate) {
return 0
}
let min = Infinity
let prev = null
for (let i = 0; i < sorted.length; i++) {
if (sorted[i] !== undefined) {
if (prev) {
min = Math.min(min, sorted[i] - prev)
}
prev = sorted[i]
}
}
return min
}