[LeetCode] 539. Minimum Time Difference

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.

最小时间差。题意是给一些以字符串list表示的时间,请你找出这中间最小的时间差。例子给的不是很好,因为list不止两个元素。

这道题不涉及算法,不过最优解比较考验你对时间的敏感度。首先,既然时间是在00:00 - 23:59这个范围内被表示出来,所以最坏也就是1440种情况,所以可以创建一个长度为1440的布尔数组记录哪些时间出现过。之后遍历这个布尔数组,看看哪两个时间之间的时间差最小。注意记得去“模”24小时。

时间O(n)

空间O(n)

Java实现

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

LeetCode 题目总结

猜你喜欢

转载自www.cnblogs.com/cnoodle/p/13369876.html