Easy to understand Java solution, no magic math involved


  • 0
    W
    1. Sort the time points.
    2. Compute the time differences of timePoint[i-1] and timePoint[i] and maintain the minimum so far.
    3. Add 24 hours to timePoint[0]
    4. Return the minimum between min and the time difference between timePoint[n-1] and timePoint[0].

    Time difference = Hour difference * 60 + Minute difference

    public class Solution {
        public int findMinDifference(List<String> timePoints) {
            Collections.sort(timePoints);
            
            int min = Integer.MAX_VALUE;
            for (int i = 1; i < timePoints.size(); i++) {
                min = Math.min(min, difference(timePoints.get(i-1), timePoints.get(i)));
            }
            
            int startHour = Integer.parseInt(timePoints.get(0).substring(0,2));
            startHour += 24;
            return Math.min(min, difference(timePoints.get(timePoints.size()-1), startHour + timePoints.get(0).substring(2,5)));
        }
        
        private int difference(String start, String end) {
            return (Integer.parseInt(end.substring(0,2)) - Integer.parseInt(start.substring(0,2))) * 60 + Integer.parseInt(end.substring(3,5)) - Integer.parseInt(start.substring(3,5));
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.