# [LeetCode] 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.

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;
}
};

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());
}
};

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 contest 177 5169. 日期之间隔几天 Number of Days Between Two Dates
LeetCode contest 177 5169. 日期之间隔几天 Number of Days Between Two Dates
0 0
LeetCode contest 183 5376. 非递增顺序的最小子序列 Minimum Subsequence in Non-Increasing Order
LeetCode contest 183 5376. 非递增顺序的最小子序列 Minimum Subsequence in Non-Increasing Order
0 0
[LeetCode] Maximum Vacation Days 最大化休假日
LeetCode wants to give one of its best employees the option to travel among N cities to collect algorithm problems.
1121 0
C# 使用TimeSpan计算两个时间差

425 0
+关注