Minimum Time Difference

Given a list of 24-hour clock time points in "Hour:Minutes" format, find the minimum minutes difference between any two time points in the list.
Example 1:

Input: ["23:59","00:00"]
Output: 1


Note:

  1. The number of time points in the given list is at least 2 and won't exceed 20000.
  2. The input time is legal and ranges from 00:00 to 23:59.

Solution:

naive

class Solution {
    public int findMinDifference(List<String> timePoints) {
        Collections.sort(timePoints);
        int min = 24 * 60;
        for (int i = 1; i < timePoints.size(); i ++) {
            String prev = timePoints.get(i - 1);
            String curr = timePoints.get(i);
            min = Math.min(min, diff(prev, curr));
        }
        min = Math.min(min, diff(timePoints.get(timePoints.size() - 1), timePoints.get(0)));
        return min;
    }
    
    private int diff(String a, String b) {
        int d = 0;
        String[] time1 = a.split(":");
        String[] time2 = b.split(":");
        int h1 = Integer.parseInt(time1[0]);
        int m1 = Integer.parseInt(time1[1]);
        int h2 = Integer.parseInt(time2[0]);
        int m2 = Integer.parseInt(time2[1]);
        if (h2 < h1) {
            h2 += 24;
        }
        int timestamp1 = h1 * 60 + m1;
        int timestamp2 = h2 * 60 + m2;
        return Math.abs(timestamp2 - timestamp1);
    }
}

bucketing:

public int findMinDifference(List<String> timePoints) {
        boolean[] mark = new boolean[24 * 60];
        int min = Integer.MAX_VALUE, max = Integer.MIN_VALUE;
        for(String time : timePoints){
            String[] t = time.split(":");
            int h = Integer.parseInt(t[0]);
            int m = Integer.parseInt(t[1]);
            if(mark[h * 60 + m]){
                return 0;
            }
            min = Math.min(min, h * 60 + m);
            max = Math.max(max, h * 60 + m);
            mark[h * 60 + m] = true;
        }
        int minDiff = Integer.MAX_VALUE, prev = 0;
        for(int i = min; i <= max; i++){   //set the range from min to max as an optimization.
            if(mark[i]){
                if(i == min){   
                    //the min and max is the special case, it looks like :
                    //0---min----max-----1440, so we have two directions to calculate the distance
                    minDiff = Math.min(minDiff, Math.min(max - min, 1440 - max + min));
                }else{
                    //normal case: just one direction.
                    minDiff = Math.min(minDiff, i - prev);
                }
                prev = i;
            }
        }
        return minDiff;
    }