0539._Minimum_Time_Difference

539. Minimum Time Difference

难度: Medium

刷题内容

原题连接

内容描述

1
2
3
4
5
6
7
8
9
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.

解题方案

思路 1
**- 时间复杂度: O(N)**- 空间复杂度: O(N)**

  • 将所有时间转换成分钟数,然后进行sort排序
  • 计算两个数之间的差值,找出最小差值即可
  • 不要忘记第一个时间与最后一个时间相比较

代码:

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
27
28
29
/**
* @param {string[]} timePoints
* @return {number}
*/
var findMinDifference = function(timePoints) {
var dayTime = 24*60;
var minTime = 24*60;
var temp = timePoints.map(function (value) {
var t = value.split(':');
return parseInt(t[0])*60+parseInt(t[1]);
});
temp.sort(function (a,b) {
return a-b;
});
for(var i =0;i<temp.length;i++){
var diff;
var f=i-1,b=i;
if(i==0)
f=temp.length-1;
if((temp[f]-temp[b])>(dayTime/2)){
diff = Math.abs(temp[f]-(temp[b]+dayTime));
minTime = diff<minTime?diff:minTime;
}else {
diff = Math.abs(temp[f]-temp[b]);
minTime = diff<minTime?diff:minTime;
}
}
return minTime===1440?0:minTime;
};