您的位置:首页 > Web前端

LeetCode Minimum Time Difference

2017-10-18 14:52 239 查看
原题链接在这里: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.

题解:

利用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 }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: