539. 最小时间差

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/minimum-time-difference
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。


鸽巢原理优化:数据规模大于24×60=1440时,直接返回0

import java.util.Collections;
import java.util.List;

class Solution {

    private int toInt(String times) {
        String[] ts = times.split(":");
        return Integer.parseInt(ts[0]) * 60 + Integer.parseInt(ts[1]);
    }

    public int findMinDifference(List<String> timePoints) {
        if (timePoints == null || timePoints.size() == 0) {
            return 0;
        }
        Collections.sort(timePoints);
        int ans = Integer.MAX_VALUE;
        for (int i = 1; i < timePoints.size(); ++i) {
            ans = Math.min(ans, toInt(timePoints.get(i)) - toInt(timePoints.get(i - 1)));
        }
        ans = Math.min(ans, toInt(timePoints.get(0)) + 24 * 60 - toInt(timePoints.get(timePoints.size() - 1)));
        return ans;
    }
}

posted @ 2022-02-17 15:40  Tianyiya  阅读(55)  评论(0)    收藏  举报