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.
把24小时表示的转成分钟。然后排序。需要注意的是要考虑“23:59”和“00:01”的时间差是2,“00:01”可以相当于“24:01”,所以要考虑最小时间和最大时间的时间差,即在排序玩的vector里,把最小的时间加上1440分钟放到最后。然后一趟循环找到最小的时间。
代码如下:

class Solution {
public:
    int findMinDifference(vector<string>& timePoints) {
        vector<int> times;
        int n = timePoints.size();
        for(int i = 0; i < n; i++)
        {
            times.push_back(str2min(timePoints[i]));
        }
        sort(times.begin(),times.end());
        times.push_back(times[0] + 1440);
        int min = times[1] - times[0];
        for(int j = 2;j<times.size();j++)
        {
            if(times[j] - times[j-1] < min)
                min = times[j] - times[j-1];
        }
        return min;
    }
private:
    //转成分钟数
    int str2min(string s)
    {
        return atoi(s.substr(0, 2).c_str()) * 60 + atoi(s.substr(3, 2).c_str());
    }
};
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容