0539. Minimum Time Difference

https://leetcode.com/problems/minimum-time-difference

Description

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

**Input:** timePoints = ["23:59","00:00"]
**Output:** 1

Example 2:

**Input:** timePoints = ["00:00","23:59","00:00"]
**Output:** 0

Constraints:

  • 2 <= timePoints <= 2 * 104

  • timePoints[i] is in the format "HH:MM".

ac

class Solution {
    public int findMinDifference(List<String> timePoints) {
        List<Integer> ms = new ArrayList<>();
        for (String s : timePoints) ms.add(htom(s));
        Collections.sort(ms);

        int min = Integer.MAX_VALUE;
        for (int i = 1; i < ms.size(); i++) {
            min = Math.min(min, ms.get(i) - ms.get(i-1));
        }
        min = Math.min(min, 60*24 - ms.get(ms.size() - 1) + ms.get(0));

        return min;
    }

    public int htom(String s) {
        String[] strs = s.split(":");
        int h = Integer.parseInt(strs[0]) * 60;
        int m = Integer.parseInt(strs[1]);
        return h + m;
    }
}

/*
1) convert to minute representation; 2) sort asc; 3) calculate diff of 2 times, careful edge case, the last one to first one mighted be smaller;
*/

Last updated