539. Minimum Time Difference

195 篇文章 0 订阅
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.

Problem URL


Solution

给一个string的list,找到这个list中表示的时间中的任意两个时间的最小差值,可能跨天。

We use a Integer list to store the value of coverted time from String to 1440(because a day has 1440 minutes). Then sort the list from small to big. Calculate the minimum difference, and a corner case, from time[0] to tomorrow’s time[time.size() - 1]. Return the smaller one.

Code
class Solution {
    public int findMinDifference(List<String> timePoints) {
        int min = Integer.MAX_VALUE;
        List<Integer> time = new ArrayList<>();
        for (int i = 0; i < timePoints.size(); i++){
            int hour = Integer.valueOf(timePoints.get(i).substring(0,2));
            int minute = Integer.valueOf(timePoints.get(i).substring(3,5));
            time.add(hour * 60 + minute);
        }
        
        Collections.sort(time, (Integer a, Integer b) -> a - b);
        
        for (int i = 1; i < time.size(); i++){
            min = Math.min(min, time.get(i) - time.get(i - 1));
        }
        int cornerCase = time.get(0) + (1440 - time.get(time.size() - 1));
        return Math.min(cornerCase, min);
    }
}

Time Complexity: O(n)
Space Complexity: O(n)


Review

We could also use Bucket sort, using a boolean int[] with size 1440 to document wether a time is showed in timepoints list. Then iteratively traverse the bucket, find minimum difference and calculate corner case.

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值