算法记录
LeetCode 题目:
给定一个 24 小时制(小时:分钟 "HH:MM" )的时间列表,找出列表中任意两个时间的最小时间差并以分钟数表示。
说明
一、题目
输入: timePoints = ["23:59","00:00"]
输出: 1
复制代码
二、分析
- 因为是字符串形式的数字,不好处理,因此我们可以先将数据转换为数字来存储。
- 将数组进行排序就可以直接求取他们之间的差值了。
- 需要注意的是两个时间是可以相互求差值的,也就是他们两之间的差值不可能超过半天,超过半天就只能用另外的一个了。
- 还有一个就是最大值和最小值之间也需要的一次求解,原因还是上面的那一条。
class Solution {
private final Integer EXCHANGE = 12 * 60;
private final Integer MAX = 24 * 60;
public int findMinDifference(List<String> timePoints) {
if(timePoints.size() > 1024) return 0;
int[] nums = new int[timePoints.size() ];
for(int i = 0; i < nums.length; i++) {
String[] times = timePoints.get(i).split(":");
nums[i] = Integer.parseInt(times[0]) * 60 + Integer.parseInt(times[1]);
}
Arrays.sort(nums);
int min = MAX;
for(int i = 1; i < nums.length; i++) {
int temp = nums[i] - nums[i - 1];
if(temp > EXCHANGE) temp = MAX - temp;
min = Math.min(min, temp);
if(min == 0) break;
}
int temp = nums[nums.length - 1] - nums[0];
if(temp > EXCHANGE) temp = MAX - temp;
min = Math.min(min, temp);
return min;
}
}
复制代码
总结
考验对于字符数字的处理。