《LeetCode之每日一题》:270.最小时间差
Posted 是七喜呀!
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了《LeetCode之每日一题》:270.最小时间差相关的知识,希望对你有一定的参考价值。
最小时间差
题目链接: 最小时间差
有关题目
给定一个 24 小时制(小时:分钟 "HH:MM")的时间列表,
找出列表中任意两个时间的最小时间差并以分钟数表示。
示例 1:
输入:timePoints = ["23:59","00:00"]
输出:1
示例 2:
输入:timePoints = ["00:00","23:59","00:00"]
输出:0
提示:
2 <= timePoints.length <= 2 * 10^4
timePoints[i] 格式为 "HH:MM"
题解
法一:排序
参考官方题解
#define MIN(a, b) ((a) < (b) ? (a) : (b))
int getMinutes(const char *s)
int a = s[0] - '0', b = s[1] - '0';
int h = a * 10 + b;
int c = s[3] - '0', d = s[4] - '0';
int m = c * 10 + d;
return h * 60 + m;
int cmp(const void *e1, const void *e2)//升序排序
return strcmp(*(char **)e1, *(char **)e2);
int findMinDifference(char ** timePoints, int timePointsSize)
qsort(timePoints, timePointsSize, sizeof(char*), cmp);
int t0Minutes = getMinutes(timePoints[0]);
int preMinutes = t0Minutes;
int ans = 1440;//24小时最多的分钟数
for (int i = 1; i < timePointsSize; i++)
int minutes = getMinutes(timePoints[i]);
ans = MIN(ans, minutes - preMinutes);//相邻时间差
preMinutes = minutes;
ans = MIN(ans, t0Minutes + 1440 - preMinutes);//首位时间差
return ans;
法二:鸽巢原理
参考官方题解
#define MIN(a, b) ((a) < (b) ? (a) : (b))
int getMinutes(const char *s)
int a = s[0] - '0', b = s[1] - '0';
int h = a * 10 + b;
int c = s[3] - '0', d = s[4] - '0';
int m = c * 10 + d;
return h * 60 + m;
int cmp(const void *e1, const void *e2)//升序排序
return strcmp(*(char **)e1, *(char **)e2);
int findMinDifference(char ** timePoints, int timePointsSize)
//鸽巢原理,总共右24 * 60 = 1440中时间,超过这个数量一定会有重复的时间,最小时间差为0
if(timePointsSize > 1440)
return 0;
qsort(timePoints, timePointsSize, sizeof(char*), cmp);
int t0Minutes = getMinutes(timePoints[0]);
int preMinutes = t0Minutes;
int ans = 1440;//24小时最多的分钟数
for (int i = 1; i < timePointsSize; i++)
int minutes = getMinutes(timePoints[i]);
ans = MIN(ans, minutes - preMinutes);//相邻时间差
preMinutes = minutes;
ans = MIN(ans, t0Minutes + 1440 - preMinutes);//首位时间差
return ans;
以上是关于《LeetCode之每日一题》:270.最小时间差的主要内容,如果未能解决你的问题,请参考以下文章
《LeetCode之每日一题》:268.寻找旋转数组中的最小值
《LeetCode之每日一题》:183.最小操作次数使数组元素相等