[leetcode]539. Minimum Time Difference

[leetcode]539. Minimum Time Difference


Analysis

今天要吃柚子—— [每天刷题并不难0.0]

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.
先对输入的字符串数组排序,然后遍历一下算差值,最后再取最小的差值就可以了。

Implement

class Solution {
public:
    int findMinDifference(vector<string>& timePoints) {
        int res = INT_MAX;
        int len = timePoints.size();
        sort(timePoints.begin(), timePoints.end());
        int h1, h2, m1, m2;
        int diff;
        string time1, time2;
        for(int i=0; i<len; i++){
            time1 = timePoints[i];
            time2 = timePoints[(i+1)%len];
            h1 = (time1[0]-'0')*10+(time1[1]-'0');
            m1 = (time1[3]-'0')*10+(time1[4]-'0');
            h2 = (time2[0]-'0')*10+(time2[1]-'0');
            m2 = (time2[3]-'0')*10+(time2[4]-'0');
            diff = (h2-h1)*60+(m2-m1);
            if(i == len-1)
                diff += 24*60;
            res = min(res, diff);
        }
        return res;
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_32135877/article/details/83211732