美文网首页
Leetcode539. 最小时间差

Leetcode539. 最小时间差

作者: LonnieQ | 来源:发表于2019-11-15 22:04 被阅读0次

    题目

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

    示例 1:

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

    备注:

    列表中时间数在 2~20000 之间。
    每个时间取值在 00:00~23:59 之间。
    

    C++解法

    #include <iostream>
    #include <vector>
    #include <map>
    #include <set>
    using namespace std;
    
    struct Time {
        int hour = 0;
        int minute = 0;
        Time(string value = "00:00") {
            if (value.size() == 5) {
                for (int i = 0; i < 2; ++i) {
                    hour = 10 * hour + (value[i] - '0');
                }
                for (int i = 3; i < 5; ++i) {
                    minute = 10 * minute + (value[i] - '0');
                }
            }
        }
        int gap(Time & time) {
            int value1 = hour * 60 + minute;
            int value2 = time.hour * 60 + time.minute;
            int minValue = value1 < value2 ? value1 : value2;
            int maxValue = value1 > value2 ? value1 : value2;
            return min(maxValue - minValue, 1440 - maxValue + minValue);
        }
    };
    class Solution {
    public:
        int findMinDifference(vector<string>& timePoints) {
            sort(timePoints.begin(), timePoints.end());
            string item;
            int minValue = INT32_MAX;
            int delta = 0;
            Time lastTime, currentTime;
            for (int i = 0; i <= timePoints.size(); ++i) {
                currentTime = Time(timePoints[i % timePoints.size()]);
                if (i != 0) {
                    delta = currentTime.gap(lastTime);
                    if (delta < minValue) minValue = delta;
                }
                lastTime = currentTime;
            }
            return minValue;
        }
    };
    int main(int argc, const char * argv[]) {
        // insert code here...
        Solution solution;
        vector<string> times;
        times = {"00:00", "23:59"};
        cout << solution.findMinDifference(times) << endl;
        return 0;
    }
    

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

    相关文章

      网友评论

          本文标题:Leetcode539. 最小时间差

          本文链接:https://www.haomeiwen.com/subject/jtkeictx.html