539. Minimum Time Difference #548
-
Topics: 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:
Example 2:
Constraints:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
The approach can be broken down as follows: Approach:
Let's implement this solution in PHP: 539. Minimum Time Difference <?php
/**
* @param String[] $timePoints
* @return Integer
*/
function findMinDifference($timePoints) {
// Convert time points to minutes
$minutes = array_map(function($time) {
list($hours, $mins) = explode(':', $time);
return $hours * 60 + $mins;
}, $timePoints);
// Sort the minutes array
sort($minutes);
$minDiff = PHP_INT_MAX;
$n = count($minutes);
// Calculate minimum difference between consecutive times
for ($i = 1; $i < $n; $i++) {
$diff = $minutes[$i] - $minutes[$i - 1];
$minDiff = min($minDiff, $diff);
}
// Check the circular difference (from last to first time)
$circularDiff = (1440 - $minutes[$n - 1]) + $minutes[0];
$minDiff = min($minDiff, $circularDiff);
return $minDiff;
}
// Example 1:
$timePoints1 = ["23:59", "00:00"];
echo findMinDifference($timePoints1) . "\n"; // Output: 1
// Example 2:
$timePoints2 = ["00:00", "23:59", "00:00"];
echo findMinDifference($timePoints2) . "\n"; // Output: 0
?> Explanation:
Time Complexity:
This solution should work efficiently within the given problem constraints. |
Beta Was this translation helpful? Give feedback.
The approach can be broken down as follows:
Approach:
Convert time points to minutes:
Each time point is in
"HH:MM"
format, so we can convert it into the total number of minutes from00:00
. For example,"23:59"
would be23 * 60 + 59 = 1439
minutes.Sort the time points:
Once all the time points are converted into minutes, sort them to calculate the differences between consecutive time points.
Handle the circular nature of the clock:
The difference between the first and last time points also needs to be considered, because of the circular nature of the clock. This can be handled by adding
1440
(24 hours) to the last time point and comparing it with the first time point.Find the mi…