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.

 

Brute force 暴力解法:O(n2), 任意两个时间点求差。效率差,忽略。

排序:O(nlgn)

 1 class Solution {
 2 public:
 3     int findMinDifference(vector<string>& timePoints) {
 4         const int SIZE=timePoints.size();
 5         if(SIZE>1440){
 6             return 0;
 7         }
 8         
 9         //sorting
10         sort(timePoints.begin(),timePoints.end());
11         int result=INT_MAX;
12         int diff;
13         for(int i=0;i<SIZE-1;i++){
14             diff=getTimeMins(timePoints[i+1])-getTimeMins(timePoints[i]);
15             result = min(result,diff);
16             if(result==0){
17                 return result;
18             }
19         }
20         
21         return min(result, getTimeMins(timePoints[0])+1440-getTimeMins(timePoints[SIZE-1]));
22     }
23 private:
24     int getTimeMins(string time24Hours){ //time24Hours in the format of "##:##"
25         return stoi(time24Hours.substr(0,2))*60+stoi(time24Hours.substr(3));
26     }
27 };

 

优化解法:比O(nlng)排序更好的是linear算法,所有的时间点总共有60*24=1440种可能,可以用数组来存该时间点是否出现过。

 1 class Solution {
 2 public:
 3     int findMinDifference(vector<string>& timePoints) {
 4         const int SIZE=1440;
 5         //there are totally 1440 different time points, if more than this number, there are at least two timepoints are the same
 6         if(timePoints.size()>SIZE){
 7             return 0;
 8         }
 9         
10         vector<bool> mask(SIZE, false);
11         for(auto timePoint: timePoints){
12             int time=getTimeMins(timePoint);
13             if(mask[time]){
14                 return 0;
15             }
16             mask[time]=true;
17         }
18         
19         int prev = -1; 
20         int first = -1; //the first timepoint
21         int last = -1;  //the last timepoint
22         int result = INT_MAX;
23         for(int i=0;i<SIZE;i++){
24             if(mask[i]){
25                 if(prev!=-1){
26                     result = min(result,i-prev);
27                 }
28                 prev = i;
29                 if(first==-1){
30                     first=i;
31                 }
32                 last = i;
33             }
34         }
35         return min(result,first+1440-last);
36     }
37 private:
38     //convert timepoint in string to a number of minutes
39     int getTimeMins(string time24Hours){ //time24Hours in the format of "##:##"
40         return stoi(time24Hours.substr(0,2))*60+stoi(time24Hours.substr(3));
41     }
42 };

 

posted @ 2018-07-25 20:20  回到明天  阅读(157)  评论(0编辑  收藏  举报