JAVA Easy Solution with O(1) space


  • 0
    J
    public class Solution {
        public int findMinDifference(List<String> timePoints) {
            Collections.sort(timePoints, new Comparator<String>() {
                
                @Override
                public int compare(String a, String b) {
                    int arr1[] = calculate(a);
                    int arr2[] = calculate(b);
                    if (arr1[0] > arr2[0]) return 1;
                    else if (arr1[0] < arr2[0]) return -1;
                    else {
                        return arr1[1] - arr2[1];
                    }
                }
            });
            
            int min = Integer.MAX_VALUE;
            String pre = timePoints.get(0);
            for (int i = 1; i < timePoints.size(); i++) {
                String time = timePoints.get(i);
                int tim1[] = calculate(pre);
                int tim2[] = calculate(time);
                if (min > cal(tim2, tim1)) min = cal(tim2, tim1);
                pre = time;
            }
            
            int a0[] = calculate(timePoints.get(0));
            int an[] = calculate(timePoints.get(timePoints.size() - 1));
            a0[0] = a0[0]+24;
            if (cal(a0, an) < min) min = cal(a0, an);
            return min;
        }
        
        private int[] calculate(String time) {
            int index = time.indexOf(":"), hour, minute;
            if (time.charAt(0) == '0') {
                if (index == 1) hour = 0;
                else hour = Integer.parseInt(time.substring(1, index));
            }
            else {
                hour = Integer.parseInt(time.substring(0, index));
            }
            
            if (time.charAt(index + 1) == '0')  {
                if (index + 1 == time.length() - 1) minute = 0;
                else minute = Integer.parseInt(time.substring(index + 2, time.length()));
            }
            else minute = Integer.parseInt(time.substring(index + 1, time.length()));
            
            int res[] = {hour, minute};
            return res;
        }
        
        private int cal(int[] a1, int[] a2) {
            return a1[0]*60 + a1[1] - a2[0]*60 - a2[1];
        }
    }

Log in to reply
 

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