diff options
author | Jack Sangdahl <[email protected]> | 2024-08-26 20:34:47 -0600 |
---|---|---|
committer | Jack Sangdahl <[email protected]> | 2024-08-26 20:34:47 -0600 |
commit | dfbbbbb78851f50c9f20a102f2f56c047046aab7 (patch) | |
tree | f8fb026a826741146fdb02b2ae6d5969db9e4cdb | |
parent | fac51ecb29d9a3030f78d09c4e3243c1445bf78f (diff) | |
download | leetcode-dfbbbbb78851f50c9f20a102f2f56c047046aab7.tar.gz leetcode-dfbbbbb78851f50c9f20a102f2f56c047046aab7.zip |
539. minimum time difference
-rw-r--r-- | min_time_difference.c | 31 | ||||
-rw-r--r-- | min_time_difference.py | 30 |
2 files changed, 61 insertions, 0 deletions
diff --git a/min_time_difference.c b/min_time_difference.c new file mode 100644 index 0000000..a0b26c2 --- /dev/null +++ b/min_time_difference.c @@ -0,0 +1,31 @@ +// 539. Minimum Time Difference +#include "leetcode.h" + +/* + * given a list of 24 hour clock time points in 'HH:MM' format, return the + * minimum minutes difference between any two time points in the list + */ + +int cmp(const void *a, const void *b) { return *((int *)a) - *((int *)b); } + +int findMinDifference(char **timePoints, int timePointsSize) { + int *minutes = (int *)malloc(timePointsSize * sizeof(int)); + for (int i = 0; i < timePointsSize; i++) { + minutes[i] = (timePoints[i][0] - '0') * 10 * 60 + + (timePoints[i][1] - '0') * 60 + (timePoints[i][3] - '0') * 10 + + (timePoints[i][4] - '0'); + } + qsort(minutes, timePointsSize, sizeof(int), cmp); + int ans = INT_MAX; + for (int i = 0; i < timePointsSize - 1; i++) + ans = fmin(ans, minutes[i + 1] - minutes[i]); + ans = fmin(ans, (24 * 60 - minutes[timePointsSize - 1]) + minutes[0]); + free(minutes); + return ans; +} + +int main() { + char *tp1[] = {"23:59", "00:00"}, *tp2[] = {"00:00", "23:59", "00:00"}; + printf("%d\n", findMinDifference((char **)tp1, ARRAY_SIZE(tp1))); // expect: 1 + printf("%d\n", findMinDifference((char **)tp2, ARRAY_SIZE(tp2))); // expect: 0 +} diff --git a/min_time_difference.py b/min_time_difference.py new file mode 100644 index 0000000..829b491 --- /dev/null +++ b/min_time_difference.py @@ -0,0 +1,30 @@ +# 539. Minimum Time Difference + +""" +given a list of 24 hour clock time points in 'HH:MM' format, return the +minimum minutes difference between any two time points in the list +""" + + +class Solution(object): + def findMinDifference(self, timePoints): + """ + :type timePoints: List[str] + :rtype: int + """ + + def convert(time): + return int(time[:2]) * 60 + int(time[3:]) + + minutes = map(convert, timePoints) + minutes.sort() + + return min( + (y - x) % (24 * 60) for x, y in zip(minutes, minutes[1:] + minutes[:1]) + ) + + +if __name__ == "__main__": + obj = Solution() + print(obj.findMinDifference(timePoints=["23:59", "00:00"])) + print(obj.findMinDifference(timePoints=["00:00", "23:59", "00:00"])) |