计算两个时间点的最小差值 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.

解决:

① 求两个时间点之间的最小差值。给数组排序,这样时间点小的就在前面了,然后我们分别把小时和分钟提取出来,计算差值,注意唯一的特殊情况就是第一个和末尾的时间点进行比较,第一个时间点需要加上24小时再做差值。O(nlgn)

class Solution { //31ms
    public int findMinDifference(List<String> timePoints) {
        int min = Integer.MAX_VALUE;
        int len = timePoints.size();
        int diff = 0;
        String[] times = new String[len];
        for (int i = 0;i < len;i ++){
            times[i] = timePoints.get(i);
        }
        Arrays.sort(times);
        for (int i = 0;i < len;i ++){
            String t1 = times[i];
            String t2 = times[(i + 1) % len];
            int h1 = (t1.charAt(0) - '0') * 10 + t1.charAt(1) - '0';
            int m1 = (t1.charAt(3) - '0') * 10 + t1.charAt(4) - '0';
            int h2 = (t2.charAt(0) - '0') * 10 + t2.charAt(1) - '0';
            int m2 = (t2.charAt(3) - '0') * 10 + t2.charAt(4) - '0';
            diff = (h2 - h1) * 60 + (m2 - m1);
            if (i == len - 1) diff += 24 * 60;
            min = Math.min(min,diff);
        }
        return min;
    }
}

② 由于时间点并不是无穷多个,而是只有1440个,所以我们建立一个大小为1440的数组来标记某个时间点是否出现过,如果之前已经出现过,说明有两个相同的时间点,直接返回0即可;若没有,将当前时间点标记为出现过。我们还需要一些辅助变量,pre表示之前遍历到的时间点,first表示按顺序排的第一个时间点,last表示按顺序排的最后一个时间点,然后我们再遍历这个mask数组,如果当前时间点出现过,再看如果first不为初始值的话,说明pre已经被更新过了,我们用当前时间点减去pre来更新结果res,然后再分别更新first,last,和pre即可。O(n)

class Solution { //41ms
    public int findMinDifference(List<String> timePoints) {
        int min = Integer.MAX_VALUE;
        int len = timePoints.size();
        int diff = 0;
        String[] times = new String[len];
        for (int i = 0;i < len;i ++){
            times[i] = timePoints.get(i);
        }
        Arrays.sort(times);
        for (int i = 0;i < len;i ++){
            String t1 = times[i];
            String t2 = times[(i + 1) % len];
            int h1 = (t1.charAt(0) - '0') * 10 + t1.charAt(1) - '0';
            int m1 = (t1.charAt(3) - '0') * 10 + t1.charAt(4) - '0';
            int h2 = (t2.charAt(0) - '0') * 10 + t2.charAt(1) - '0';
            int m2 = (t2.charAt(3) - '0') * 10 + t2.charAt(4) - '0';
            diff = (h2 - h1) * 60 + (m2 - m1);
            if (i == len - 1) diff += 24 * 60;
            min = Math.min(min,diff);
        }
        return min;
    }
}

转载于:https://my.oschina.net/liyurong/blog/1605046

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值