539. Minimum Time Difference

来源:互联网 发布:认证报名保存数据失败 编辑:程序博客网 时间:2024/05/16 14:19

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 ;    }};



0 0