力扣题-12.12
[力扣刷题攻略] Re:从零开始的力扣刷题生活
力扣题1:539. 最小时间差
解题思想:将字符串的时间形式换成数字形式的时间,然后计算差值即可,最重要的是最小的值加上一天的时间加入到数组最后(计算第一个和最后一个时间的时间差)
class Solution(object):
def findMinDifference(self, timePoints):
"""
:type timePoints: List[str]
:rtype: int
"""
if len(timePoints)>24*60:
return 0
total = []
for i in range(len(timePoints)):
time = timePoints[i].split(":")
minute = int(time[0])*60+int(time[1])
total.append(minute)
total = sorted(total)
total.append(total[0]+24*60)
result = 24*60
for i in range(1,len(total)):
result = min(result,total[i]-total[i-1])
return result
class Solution {
public:
int findMinDifference(vector<string>& timePoints) {
if (timePoints.size() > 24 * 60) {
return 0;
}
std::vector<int> total;
for (const auto& timePoint : timePoints) {
int colonIndex = timePoint.find(":");
int hour = std::stoi(timePoint.substr(0, colonIndex));
int minute = std::stoi(timePoint.substr(colonIndex + 1));
int minutes = hour * 60 + minute;
total.push_back(minutes);
}
std::sort(total.begin(), total.end());
total.push_back(total[0] + 24 * 60);
int result = 24 * 60;
for (int i = 1; i < total.size(); ++i) {
result = std::min(result, total[i] - total[i - 1]);
}
return result;
}
};