Friday, August 21, 2020

539. Minimum Time Difference -------M

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.

 A:

class Solution {
public:
    int findMinDifference(vector<string>& timePoints) {
        int n = timePoints.size();
        vector<int> V;
        for(auto str:timePoints)
            V.push_back(getMinutes(str));
        sort(V.begin(), V.end());
        int res =INT_MAX;
        for(int i = 0;i< n;i++){
            int small = V[i];
            int big = V[ (i+1)%n];
            if(i==n-1){
                res = min(res, big + 24*60-small);
            }else{
                res = min(res, big - small);
            }
        }
        return res;
    }
private:    
    int getMinutes(string str){
        int index = str.find(':');
        string t = str.substr(0,index);
        string m = str.substr(index+1);
        return 60* stoi(t) + stoi(m);
    }
};


No comments:

Post a Comment