最小时间差

最小时间差

题目:

给定一个 24 小时制(小时:分钟 "HH:MM")的时间列表,找出列表中任意两个时间的最小时间差并以分钟数表示。

示例 1:
输入:timePoints = ["23:59","00:00"]
输出:1

示例 2:
输入:timePoints = ["00:00","23:59","00:00"]
输出:0
class Solution {
    public int findMinDifference(List<String> timePoints) {
        Collections.sort(timePoints);
        int size = timePoints.size();
        int ans = Integer.MAX_VALUE;
        for(int i = 0; i < size - 1; i++) {
            int pre = getMinutes(timePoints.get(i).split(":"));
            int next = getMinutes(timePoints.get(i + 1).split(":"));
            int res = next - pre;
            ans = Math.min(res, ans);
        }
        int pre = getMinutes(timePoints.get(0).split(":"));
        int next = getMinutes(timePoints.get(size - 1).split(":"));
        ans = Math.min(ans, pre + 24 * 60 - next);
        return ans;
    }

    private int getMinutes(String[] str) {
        int hour = Integer.parseInt(str[0]);
        int minute = Integer.parseInt(str[1]);
        return hour * 60 + minute;
    }
}

你可能感兴趣的:(leetcode-数组,java)