Very Easy To Understand O(n) Java Solution


  • 0
    J
    class Solution {
        public int findMinDifference(List<String> timePoints) {
            List<Integer> timePointsInMinutes = convertHoursToMin(timePoints);
            Collections.sort(timePointsInMinutes);
            int min = Integer.MAX_VALUE;
            
            for (int i = 1; i < timePointsInMinutes.size(); i++) {
                int diff1 = timePointsInMinutes.get(i) - timePointsInMinutes.get(i - 1);
                int diff2 = (24 * 60) - diff1;
                if (min > Math.min(diff1, diff2)) {
                    min = Math.min(diff1, diff2);
                }   
            }
            
            int diffBetweenFirstAndLastTimePoints1 = timePointsInMinutes.get(timePointsInMinutes.size() - 1) - timePointsInMinutes.get(0);
            int diffBetweenFirstAndLastTimePoints2 = (24 * 60) - diffBetweenFirstAndLastTimePoints1;
            
            if (min > Math.min(diffBetweenFirstAndLastTimePoints1, diffBetweenFirstAndLastTimePoints2)) {
                min = Math.min(diffBetweenFirstAndLastTimePoints1, diffBetweenFirstAndLastTimePoints2);
            }
            
            return min;
        }
        
        private List<Integer> convertHoursToMin(List<String> timePoints) {
            List<Integer> timePointsInMinutes = new ArrayList<Integer>();
            for (String s : timePoints) {
                String[] arr = s.split(":");
                int hour = Integer.parseInt(arr[0]);
                int min = Integer.parseInt(arr[1]);
                int totalMin = (hour * 60) + min;
                timePointsInMinutes.add(totalMin);
            }
            return timePointsInMinutes;
        }
    }
    

Log in to reply
 

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