539. 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.

找列表中时间差最小的两个时间点。

想法是先把时间点化为分钟数,用treeset,动态排序;

需要注意循环问题,比如example,output应该是1,也就是24*60 + 0 - (23*60 + 59),而不是(23*60 + 59) - 0;

    public int findMinDifference(List<String> timePoints) {
        int min = Integer.MAX_VALUE, max = Integer.MIN_VALUE;
        int res = Integer.MAX_VALUE;
        TreeSet<Integer> set = new TreeSet<>();
        
        for (String t : timePoints) {
            String[] array = t.split(":");
            int m = Integer.parseInt(array[0]) * 60 + Integer.parseInt(array[1]);
            min = Math.min(min, m);
            max = Math.max(max, m);
            
            Integer c = set.ceiling(m);//大于当前值的最小值
            if (c != null) {
                res = Math.min(res, c - m);
            }
            Integer f = set.floor(m);//小于当前值的最大值
            if (f != null) {
                res = Math.min(res, m - f);
            }
            
            set.add(m);
        }
        
        return Math.min(res, 24*60 + min - max);//处理循环问题
    }

时间复杂度O(nlogn),因为用到了treeset。

 

discuss:

    public int findMinDifference(List<String> timePoints) {
        boolean[] mark = new boolean[24 * 60];//时间点有限
        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;
            mark[h * 60 + m] = true;//标识
        }
        
        int prev = 0, min = Integer.MAX_VALUE;
        int first = Integer.MAX_VALUE, last = Integer.MIN_VALUE;
        for (int i = 0; i < 24 * 60; i++) {
            if (mark[i]) {
                if (first != Integer.MAX_VALUE) {//小于当前值的最大值
                    min = Math.min(min, i - prev);
                }
                first = Math.min(first, i);
                last = Math.max(last, i);
                prev = i;
            }
        }
        
        min = Math.min(min, (24 * 60 - last + first));//处理循环问题
        
        return min;
    }

因为时间点有限,所以可以使用数组代替排序,时间复杂度O(n)。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值