# 539. Minimum Time Difference

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:

1. The number of time points in the given list is at least 2 and won’t exceed 20000.
2. The input time is legal and ranges from 00:00 to 23:59.

``````class Solution {
public:
int findMinDifference(vector<string>& timePoints) {
int res = INT_MAX, n = timePoints.size(), diff = 0;
sort(timePoints.begin(), timePoints.end());
for (int i = 0; i < n; ++i) {
string t1 = timePoints[i], t2 = timePoints[(i + 1) % n];
int h1 = (t1[0] - '0') * 10 + t1[1] - '0';
int m1 = (t1[3] - '0') * 10 + t1[4] - '0';
int h2 = (t2[0] - '0') * 10 + t2[1] - '0';
int m2 = (t2[3] - '0') * 10 + t2[4] - '0';
diff = (h2 - h1) * 60 + (m2 - m1);
if (i == n - 1) diff += 24 * 60;
res = min(res, diff);
}
return res;
}
};
``````

``````class Solution {
public:
int findMinDifference(vector<string>& timePoints) {
int res = INT_MAX, n = timePoints.size();
vector<int> nums;
for (string str : timePoints) {
int h = stoi(str.substr(0, 2)), m = stoi(str.substr(3));
nums.push_back(h * 60 + m);
}
sort(nums.begin(), nums.end());
for (int i = 1; i < n; ++i) {
res = min(res, nums[i] - nums[i - 1]);
}
return min(res, 1440 + nums[0] - nums.back());
}
};
``````

``````class Solution {
public:
int findMinDifference(vector<string>& timePoints) {
int res = INT_MAX, pre = 0, first = INT_MAX, last = INT_MIN;
for (string str : timePoints) {
int h = stoi(str.substr(0, 2)), m = stoi(str.substr(3));
if (mask[h * 60 + m] == 1) return 0;
mask[h * 60 + m] = 1;
}
for (int i = 0; i < 1440; ++i) {
if (first != INT_MAX) {
res = min(res, i - pre);
}
first = min(first, i);
last = max(last, i);
pre = i;
}
}
return min(res, 1440 + first - last);
}
};
``````

https://discuss.leetcode.com/topic/83250/easy-c-solution

https://discuss.leetcode.com/topic/82573/verbose-java-solution-bucket

https://discuss.leetcode.com/topic/82575/java-o-nlog-n-o-n-time-o-1-space-solutions

LeetCode All in One 题目讲解汇总(持续更新中…)

 微信打赏 Venmo 打赏
（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，试运营期间前五十位可享受半价优惠～）

×

Help us with donation