Leetcode——539. Minimum Time Difference

题目原址

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

题目描述

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:

  • The number of time points in the given list is at least 2 and won’t exceed 20000.
  • The input time is legal and ranges from 00:00 to 23:59.

解题思路

给定一个时间集合,找到集合中两两时间点相差最小的时间

  • 首先利用Collections类的sort方法对集合时间进行排序
  • 利用split方法将时间按照:分开,将一个时:分形式的时间化成分,两两比较时间差最小的差值
  • 最后比较第一个时间和最后一个时间,因为这两个时间可能存在00:00和23:59这种情况。出现这种情况需要将00点所在的时间值+24 - 23点所在的时间

AC代码

class Solution {
    public int findMinDifference(List<String> timePoints) {
        String[] string = new String[timePoints.size()];
        int[][] arr= new int[timePoints.size()][2];
        int min = Integer.MAX_VALUE;
        //对时间进行排序
        Collections.sort(timePoints, new Comparator<String>(){

            @Override
            public int compare(String o1, String o2) {
                String[] time1 = o1.split(":");
                String[] time2 = o2.split(":");
                int t1 = Integer.parseInt(time1[0]) * 60 + Integer.parseInt(time1[1]);
                int t2 = Integer.parseInt(time2[0]) * 60 + Integer.parseInt(time2[1]);
                return t1 - t2;
            }

        });

        for(int i = 0; i < timePoints.size() - 1; i++) {
            String[] time1 = timePoints.get(i).split(":");
            String[] time2 = timePoints.get(i + 1).split(":");
            int t1 = Integer.parseInt(time1[0]) * 60 + Integer.parseInt(time1[1]);
            int t2 = Integer.parseInt(time2[0]) * 60 + Integer.parseInt(time2[1]);
            min = Math.min(min, t2 - t1);
        }

        String[] time1 = timePoints.get(0).split(":");
        String[] time2 = timePoints.get(timePoints.size() - 1).split(":");
        int t1 = Integer.parseInt(time1[0]) * 60 + Integer.parseInt(time1[1]);
        int t2 = Integer.parseInt(time2[0]) * 60 + Integer.parseInt(time2[1]);

        if(min > t1 + 24 * 60 - t2)
            min = t1 + 24 * 60 - t2;
        return min;        
    }
}

感谢

https://blog.csdn.net/mcf171/article/details/61616086

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值