LeetCode 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:

  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.

题解:

利用bucket sort. 把时间转化成的位置标记成true. 若是之前已经标记了说明有duplicate, 可以直接return 0.

从头到尾iterate buckets维护最小diff. 再和首尾相差的diff比较取出最小值.

Time Complexity: O(timePoints.size() + 24*60).

Space: O(24*60).

AC Java:

 1 class Solution {
 2     public int findMinDifference(List<String> timePoints) {
 3         boolean [] mark = new boolean[24*60];
 4         for(String timeStr : timePoints){
 5             String [] timeArr = timeStr.split(":");
 6             int time = Integer.valueOf(timeArr[0])*60 + Integer.valueOf(timeArr[1]);
 7             
 8             if(mark[time]){
 9                 return 0;
10             }
11             
12             mark[time] = true;
13         }
14         
15         int min = Integer.MAX_VALUE;
16         int pre = 0;
17         int first = Integer.MAX_VALUE;
18         int last = Integer.MIN_VALUE;
19         for(int i = 0; i<24*60; i++){
20             if(mark[i]){
21                 if(first != Integer.MAX_VALUE){
22                     min = Math.min(min, i-pre);
23                 }
24                 pre = i;
25                 first = Math.min(first, i);
26                 last = Math.max(last, i);
27             }
28         }
29         
30         min = Math.min(min, 24*60+first-last);
31         return min;
32     }
33 }

 

转载于:https://www.cnblogs.com/Dylan-Java-NYC/p/7686650.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值