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.

題目鏈接:https://leetcode.com/problems/minimum-time-difference/#/description

題目大意:給定一個24小時制的一組時間,求出任意兩個時間的最小間隔。

思路:將24小時每一分鐘映射到一個長度爲24*60的hash表中,時間複雜度爲O(N)。

參考代碼:

class Solution {
public:
    int findMinDifference(vector<string>& timePoints) {
        int n = timePoints.size() ;
        if ( n < 2 )
            return 0 ;
        int ans = INT_MAX , N = 24 * 60 , pre = 0 , maxer = 0 ;
        vector <bool> has ( N , false ) ;
        for ( int i = 0 ; i < n ; i ++ )
        {
            string s = timePoints[i] ;
            int k = s.find ( ':' ) ;
            int h = atoi ( s.substr ( 0 , k ).c_str() ) , m = atoi ( s.substr ( k + 1 ).c_str() ) ;
            int index = h * 60 + m ;
            if ( index == N )
                index = 0 ;
            if ( has[index] )
                return 0 ;
            has[index] = true ;
        }
        bool judge = true ;
        for ( int i = 0 ; i < N ; i ++ )
        {
            if ( has[i] )
            {
                if ( judge )
                {
                    pre = i ;
                    judge = false ;
                    maxer = i + N ;
                }
                else
                {
                    ans = min ( ans , i - pre ) ;
                    pre = i ;
                }
            }
        }
        ans = min ( ans , maxer - pre ) ;
        return ans ;
    }
};



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章