题目原址
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.
解题思路
给定一个时间集合,找到集合中两两时间点相差最小的时间
- 首先利用Collections类的sort方法对集合时间进行排序
- 利用split方法将时间按照
:
分开,将一个时:分形式的时间化成分,两两比较时间差最小的差值 - 最后比较第一个时间和最后一个时间,因为这两个时间可能存在00:00和23:59这种情况。出现这种情况需要将00点所在的时间值+24 - 23点所在的时间
AC代码
class Solution {
public int findMinDifference(List<String> timePoints) {
String[] string = new String[timePoints.size()];
int[][] arr= new int[timePoints.size()][2];
int min = Integer.MAX_VALUE;
//对时间进行排序
Collections.sort(timePoints, new Comparator<String>(){
@Override
public int compare(String o1, String o2) {
String[] time1 = o1.split(":");
String[] time2 = o2.split(":");
int t1 = Integer.parseInt(time1[0]) * 60 + Integer.parseInt(time1[1]);
int t2 = Integer.parseInt(time2[0]) * 60 + Integer.parseInt(time2[1]);
return t1 - t2;
}
});
for(int i = 0; i < timePoints.size() - 1; i++) {
String[] time1 = timePoints.get(i).split(":");
String[] time2 = timePoints.get(i + 1).split(":");
int t1 = Integer.parseInt(time1[0]) * 60 + Integer.parseInt(time1[1]);
int t2 = Integer.parseInt(time2[0]) * 60 + Integer.parseInt(time2[1]);
min = Math.min(min, t2 - t1);
}
String[] time1 = timePoints.get(0).split(":");
String[] time2 = timePoints.get(timePoints.size() - 1).split(":");
int t1 = Integer.parseInt(time1[0]) * 60 + Integer.parseInt(time1[1]);
int t2 = Integer.parseInt(time2[0]) * 60 + Integer.parseInt(time2[1]);
if(min > t1 + 24 * 60 - t2)
min = t1 + 24 * 60 - t2;
return min;
}
}