给定一个 24 小时制(小时:分钟 "HH:MM")的时间列表,找出列表中任意两个时间的最小时间差并以分钟数表示。
示例 1:
输入:timePoints = ["23:59","00:00"] 输出:1
示例 2:
输入:timePoints = ["00:00","23:59","00:00"] 输出:0
提示:
2 <= timePoints.length <= 2 * 104
timePoints[i]
格式为 "HH:MM"
class Solution:
def findMinDifference(self, timePoints: List[str]) -> int:
if len(timePoints) > 24 * 60:
return 0
mins = sorted(int(t[:2]) * 60 + int(t[3:]) for t in timePoints)
mins.append(mins[0] + 24 * 60)
res = mins[-1]
for i in range(1, len(mins)):
res = min(res, mins[i] - mins[i - 1])
return res
class Solution {
public int findMinDifference(List<String> timePoints) {
if (timePoints.size() > 24 * 60) {
return 0;
}
List<Integer> mins = new ArrayList<>();
for (String t : timePoints) {
String[] time = t.split(":");
mins.add(Integer.parseInt(time[0]) * 60 + Integer.parseInt(time[1]));
}
Collections.sort(mins);
mins.add(mins.get(0) + 24 * 60);
int res = 24 * 60;
for (int i = 1; i < mins.size(); ++i) {
res = Math.min(res, mins.get(i) - mins.get(i - 1));
}
return res;
}
}
class Solution {
public:
int findMinDifference(vector<string>& timePoints) {
if (timePoints.size() > 24 * 60)
return 0;
vector<int> mins;
for (auto t : timePoints)
mins.push_back(stoi(t.substr(0, 2)) * 60 + stoi(t.substr(3)));
sort(mins.begin(), mins.end());
mins.push_back(mins[0] + 24 * 60);
int res = 24 * 60;
for (int i = 1; i < mins.size(); ++i)
res = min(res, mins[i] - mins[i - 1]);
return res;
}
};
func findMinDifference(timePoints []string) int {
if len(timePoints) > 24*60 {
return 0
}
var mins []int
for _, t := range timePoints {
time := strings.Split(t, ":")
h, _ := strconv.Atoi(time[0])
m, _ := strconv.Atoi(time[1])
mins = append(mins, h*60+m)
}
sort.Ints(mins)
mins = append(mins, mins[0]+24*60)
res := 24 * 60
for i := 1; i < len(mins); i++ {
res = min(res, mins[i]-mins[i-1])
}
return res
}
function findMinDifference(timePoints: string[]): number {
const mins = timePoints
.map(item => Number(item.slice(0, 2)) * 60 + Number(item.slice(3, 5)))
.sort((a, b) => a - b);
const n = mins.length;
let res = Infinity;
for (let i = 0; i < n - 1; i++) {
res = Math.min(res, mins[i + 1] - mins[i]);
}
const first = mins[0] + 24 * 60;
const last = mins[n - 1];
res = Math.min(res, first - last);
return res;
}