zoukankan      html  css  js  c++  java
  • LC 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.

    比较笨的一种方法就是我的方法,每次转成分钟然后做差就行了,注意要算补数求最小,计算时头和尾也要计算一次差值。

    Runtime: 24 ms, faster than 25.52% of C++ online submissions for Minimum Time Difference.

    class Solution {
    public:
      int minutediff(string time1, string time2){
        int hour1 = atoi(time1.substr(0,2).c_str());
        int hour2 = atoi(time2.substr(0,2).c_str());
        int minute1 = atoi(time1.substr(3,2).c_str());
        int minute2 = atoi(time2.substr(3,2).c_str());
        minute1 = hour1 * 60 + minute1;
        minute2 = hour2 * 60 + minute2;
        int dif1 = abs(minute1 - minute2);
        int dif2 = abs(24 * 60 - dif1);
        return min(dif1, dif2);
      }
      
      
      int findMinDifference(vector<string>& timePoints) {
        sort(timePoints.begin(), timePoints.end());
        vector<int> timedif(timePoints.size(),INT_MAX);
        for(int i=1; i<timePoints.size(); i++){
          timedif[i] = minutediff(timePoints[i],timePoints[i-1]);
        }
        timedif[0] = minutediff(timePoints[0], timePoints.back());
        int ret = *min_element(timedif.begin(),timedif.end());
        return ret;
      }
    };

    这一种做法时间不快因为每一次时间需要进行两次转换,下面看怎么进行一次转换。

    另一种高级的做法,因为总共就24*60种可能,不如开一个24*60的数组,计算差值,妙!

    class Solution {
    public:
        int findMinDifference(vector<string>& timePoints) {
            vector<int> v(24 * 60, 0);
            int r = INT_MAX, begin = 24 * 60, last = -24 * 60;
            for (string & p : timePoints) {
                int t = stoi(p.substr(0, 2)) *  60 + stoi(p.substr(3, 2));
                if (v[t] == 1) return 0;
                v[t] = 1;
            }
            for (int i = 0; i < 24 * 60; i++) {
                if (v[i]) {
                    r = min(r, i - last);
                    begin = min(begin, i);
                    last = i;
                }
            }
            return min(r, begin + 24 * 60 - last);
        }
    };
  • 相关阅读:
    第四次实验报告
    第三次实验报告
    第五章循环结构课后反思
    第二次实验报告
    第一次实验报告
    第一次作业
    第九章 结构体与共用体
    第八章实验报告
    第七章数组实验
    第六章函数与宏定义实验报告(2)
  • 原文地址:https://www.cnblogs.com/ethanhong/p/10179533.html
Copyright © 2011-2022 走看看