LeetCode-539 最小时间差

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/minimum-time-difference

题目描述

给定一个 24 小时制(小时:分钟 "HH:MM")的时间列表,找出列表中任意两个时间的最小时间差并以分钟数表示。

 

示例 1:

输入:timePoints = ["23:59","00:00"]
输出:1


示例 2:

输入:timePoints = ["00:00","23:59","00:00"]
输出:0
 

提示:

2 <= timePoints <= 2 * 104
timePoints[i] 格式为 "HH:MM"

 

解题思路

将输入的时间进行排序,那么时间差就会出现在相邻的时间之间,遍历所有相邻的时间,找出最小值,值得注意的是,时间是可循环的,所以,最大的时间到次日最小时间也是需要考虑进去的。

代码展示

class Solution {
public:
    int ToMinute(string s)
    {
        return (s[0] - '0') * 600 + (s[1] - '0') * 60 + (s[3] - '0') * 10 + s[4] - '0';
    }
    int findMinDifference(vector<string>& timePoints) {
        int n = timePoints.size();
        if(n > 1440) return 0;
        sort(timePoints.begin(), timePoints.end());
        int iLast = ToMinute(timePoints[0]);
        int iMin = INT_MAX;
        for(int i = 1; i < n; i++)
        {
            int iCur = ToMinute(timePoints[i]);
            if(iCur - iLast < iMin)
            {
                iMin = iCur - iLast;
            }
            iLast = iCur;
        }
        if(1440 + ToMinute(timePoints[0]) - ToMinute(timePoints[n-1]) < iMin)
        {
            iMin = 1440 + ToMinute(timePoints[0]) - ToMinute(timePoints[n-1]);
        }
        return iMin;
    }
};

 

运行结果

LeetCode-539 最小时间差

 

 

上一篇:《深入理解Java虚拟机》学习笔记(二)


下一篇:Java_格式字符串的使用