LeetCode 539. Minimum Time Difference

版权声明:本文为博主原创文章,转载请注明出处,谢谢!

版权声明:本文为博主原创文章,转载请注明出处:http://blog.jerkybible.com/2017/03/18/LeetCode-539-Minimum-Time-Difference/

访问原文「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.

题意解析

计算最短的时间间隔,注意24小时制值得变化。

解法分析

将时间进行转换,转换成整型,转换方式为hour*24+minute,然后排序,最后计算就可以了。

解题代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
public int findMinDifference(List<String> timePoints) {
int[] timeRevert = new int[timePoints.size()];
for (int i = 0; i < timePoints.size(); i++) {
String timePoint = timePoints.get(i);
String[] timeParts = timePoint.split(":");
int hour = Integer.valueOf(timeParts[0].trim());
int minute = Integer.valueOf(timeParts[1].trim());
int revert = hour * 60 + minute;
timeRevert[i] = revert;
}
Arrays.sort(timeRevert);
int min = Integer.MAX_VALUE;
for (int i = 0; i < timeRevert.length; i++) {
if (i < timeRevert.length - 1) {
if (timeRevert[i + 1] - timeRevert[i] < min) {
min = timeRevert[i + 1] - timeRevert[i];
}
} else {
if (timeRevert[0] + 24 * 60 - timeRevert[i] < min) {
min = timeRevert[0] + 24 * 60 - timeRevert[i];
}
}
}
return min;
}
Jerky Lu wechat
欢迎加入微信公众号