​LeetCode刷题实战539:最小时间差

算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从LeetCode上面选 !

今天和大家聊的问题叫做 最小时间差,我们先来看题面:

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

Given a list of 24-hour clock time points in "HH:MM" format, return the minimum minutes difference between any two time-points in the list.

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

示例                         

示例 1:

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

示例 2:

输入:timePoints = ["00:00","23:59","00:00"]
输出:0

解题

仿时间戳,以分钟为单位把每个时间的时间戳给计算出来

这里要计算当前时间和当前时间后一天这个时间点的的时间,主要是为了防止跨夜计算的情况,比如题目里的输入:timePoints = ["23:59","00:00"],输出:1

class Solution {
        public int findMinDifference(List<String> timePoints) {
            int size=timePoints.size();
            //仿时间戳做个今明两天的数组
            int[] time=new int[size*2];
            for (int i = 0,idx=0; i <size; idx=idx+2,i++) {
                String[] split = timePoints.get(i).split(":");
                int h = Integer.parseInt(split[0]);
                int m = Integer.parseInt(split[1]);
                //计算当前时间的时间戳
                time[idx]=h*60+m;

                //计算后一天当前时间的时间戳
                //60*24=1440分钟
                time[idx+1]=time[idx]+1440;
            }

            Arrays.sort(time);

            int res=Integer.MAX_VALUE;
            for (int i = 0; i+1 < time.length; i++) {
                res=Math.min((time[i+1]-time[i]),res);
            }
            return res;
        }
    }

好了,今天的文章就到这里,如果觉得有所收获,请顺手点个在看或者转发吧,你们的支持是我最大的动力 。

上期推文:

LeetCode1-520题汇总,希望对你有点帮助!

LeetCode刷题实战521:最长特殊序列 Ⅰ

LeetCode刷题实战522:最长特殊序列 II

LeetCode刷题实战523:连续的子数组和

LeetCode刷题实战524:通过删除字母匹配到字典里最长单词

LeetCode刷题实战525:连续数组

LeetCode刷题实战526:优美的排列

LeetCode刷题实战527:单词缩写

LeetCode刷题实战528:按权重随机选择

LeetCode刷题实战529:扫雷游戏

LeetCode刷题实战530:二叉搜索树的最小绝对差

LeetCode刷题实战531:孤独像素 I

LeetCode刷题实战532:数组中的K-diff数对

LeetCode刷题实战533:孤独像素 II

LeetCode刷题实战534:游戏玩法分析 III

LeetCode刷题实战535:TinyURL 的加密与解密

LeetCode刷题实战536:从字符串生成二叉树

LeetCode刷题实战537:复数乘法

LeetCode刷题实战538:把二叉搜索树转换为累加树

05d1433f66ae3b44de854cf22a65cc7e.png

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序员小猿666

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值