|
| 1 | +package solutions; |
| 2 | + |
| 3 | + |
| 4 | +import java.util.ArrayList; |
| 5 | +import java.util.Collections; |
| 6 | +import java.util.List; |
| 7 | + |
| 8 | +// [Problem] https://leetcode.com/problems/minimum-time-difference |
| 9 | +class MinimumTimeDifference { |
| 10 | + // Sorting |
| 11 | + // O(nlogn) time, O(n) space |
| 12 | + public int findMinDifference(List<String> timePoints) { |
| 13 | + List<Integer> numTimes = new ArrayList<>(); |
| 14 | + for (String timePoint : timePoints) { |
| 15 | + int hour = Integer.parseInt(timePoint.substring(0, 2)); |
| 16 | + int minute = Integer.parseInt(timePoint.substring(3)); |
| 17 | + numTimes.add(60 * hour + minute); |
| 18 | + } |
| 19 | + Collections.sort(numTimes); |
| 20 | + int minDiff = Integer.MAX_VALUE; |
| 21 | + for (int i = 1; i < numTimes.size(); i++) { |
| 22 | + int diff = numTimes.get(i) - numTimes.get(i - 1); |
| 23 | + minDiff = Math.min(diff, minDiff); |
| 24 | + } |
| 25 | + int cornerDiff = 1440 + numTimes.get(0) - numTimes.get(numTimes.size() - 1); |
| 26 | + return Math.min(cornerDiff, minDiff); |
| 27 | + } |
| 28 | + |
| 29 | + // Test |
| 30 | + public static void main(String[] args) { |
| 31 | + MinimumTimeDifference solution = new MinimumTimeDifference(); |
| 32 | + |
| 33 | + List<String> input1 = List.of("23:59", "00:00"); |
| 34 | + int expectedOutput1 = 1; |
| 35 | + int actualOutput1 = solution.findMinDifference(input1); |
| 36 | + System.out.println("Test 1 passed? " + (expectedOutput1 == actualOutput1)); |
| 37 | + |
| 38 | + List<String> input2 = List.of("00:00", "23:59", "00:00"); |
| 39 | + int expectedOutput2 = 0; |
| 40 | + int actualOutput2 = solution.findMinDifference(input2); |
| 41 | + System.out.println("Test 2 passed? " + (expectedOutput2 == actualOutput2)); |
| 42 | + } |
| 43 | +} |
0 commit comments