Leetcode 539. 最小时间差

博客围绕Leetcode 539最小时间差问题展开,给定24小时制时间列表,需找出任意两个时间的最小时间差并以分钟数表示,给出了示例及输入输出情况,还展示了Java解法的执行结果,用时2ms,内存消耗38.1MB,击败了多数用户。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Leetcode 539. 最小时间差

  1. 最小时间差

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

示例 1:

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

示例 2:

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

提示:

2 <= timePoints <= 2 * 104
timePoints[i] 格式为 "HH:MM"
class Solution {
	/**
	 *利用桶排序的思想将列表中的每个数放到对应的桶中
	 */
    public int findMinDifference(List<String> timePoints) {
        if(timePoints.size() > 24 * 60)return 0;
        boolean[] data = new boolean[24 * 60];
        int min = 24 * 60;
        //先判断列表中是否有相同的值
        for(String str:timePoints){
            int index = getIndex(str);
            if(data[index]) return 0;
            data[index] = true;
        }
        
        int firstTrue = -1;
        int preTrue = -1;
        for(int i = 0;i < data.length;i++){
        	//寻找第一个数
            if(data[i]&&preTrue == -1){
                firstTrue = i;
                preTrue = i;
                continue;
            }
            //如果当前的数存在,就与上一个数相减的出最小值,并记录现在的位置
            if(data[i]){
                int flag = i - preTrue;
                if(flag == 1) return 1;
                min = min < flag?min : flag;
                preTrue = i;
            }
        }
        //将最后一个存在的数和第一个存在的数之间存在的循环差值
        int reverse = 24 * 60 - (preTrue - firstTrue);
        return min < reverse?min : reverse;
    }
    /**
     *将字符串转化为数字
     */
    public int getIndex(String str){
        Integer num1 = Integer.parseInt(str.substring(0,2));
        Integer num2 = Integer.parseInt(str.substring(3,5));
        return num1 * 60 + num2; 
    }
}

执行结果:
通过
显示详情
执行用时:2 ms, 在所有 Java 提交中击败了98.42% 的用户
内存消耗:38.1 MB, 在所有 Java 提交中击败了91.39% 的用户

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值