Java solution, Time O(nlogn), no extra space


  • 0
    M
    public class Solution {
        public int findMinDifference(List<String> timePoints) {
            Collections.sort(timePoints, new Comparator<String>(){
                @Override
                public int compare(String t1, String t2){
                    int compHour = t1.substring(0,2).compareTo(t2.substring(0,2));
                    if(compHour != 0) return compHour;
                    else return t1.substring(3).compareTo(t2.substring(3));
                }
            });
            final int N = timePoints.size();
            final int MAX_TIME = 24*60;
            int minDiff = Math.min(
                (getTime(timePoints.get(N-1))-getTime(timePoints.get(0))+MAX_TIME)%MAX_TIME, (getTime(timePoints.get(0))-getTime(timePoints.get(N-1)) + MAX_TIME) % MAX_TIME);
            for(int i=1; i<N; i++){
                int diff = (getTime(timePoints.get(i))-getTime(timePoints.get(i-1)) + MAX_TIME) % MAX_TIME;
                minDiff = Math.min(minDiff, diff);
            }
            return minDiff;
        }
        
        private int getTime(String timePoint){
            return Integer.valueOf(timePoint.substring(0,2))*60 + Integer.valueOf(timePoint.substring(3));
        }
    }
    

Log in to reply
 

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