949. Largest Time for Given Digits

Given an array of 4 digits, return the largest 24 hour time that can be made.

The smallest 24 hour time is 00:00, and the largest is 23:59.  Starting from 00:00, a time is larger if more time has elapsed since midnight.

Return the answer as a string of length 5.  If no valid time can be made, return an empty string.

Example 1:

Input: [1,2,3,4]
Output: "23:41"

Example 2:

Input: [5,5,5,5]
Output: ""

Note:

  1. A.length == 4
  2. 0 <= A[i] <= 9

过滤掉不匹配的时间,然后更新最大时间即可。

#include <iostream> 
#include <algorithm>
#include <vector>
using namespace std;

class Solution
{
    public:
        string largestTimeFromDigits(vector<int>& a)
        {
            vector<int> b(4,-1);
            sort(a.begin(),a.end());
            do
            {
                if(a[0]>2)
                    continue;
                if(a[0]*10+a[1]>=24)
                    continue;
                if(a[2]*10+a[3]>=60)
                    continue;
                    
                if(a[0]>b[0]||a[1]>b[1]||a[2]>b[2]||a[3]>b[3])
                    for(int i=0;i<4;++i)
                        b[i]=a[i];
            }while(next_permutation(a.begin(),a.end()));
            if(b[0]==-1)
                return "";
            return to_string(b[0])+to_string(b[1])+":"+to_string(b[2])+to_string(b[3]);
        }    
};
int main()
{
    Solution s;
    int a[4]={1,2,3,4};
    vector<int> t(a,a+4);
    cout<<s.largestTimeFromDigits(t)<<endl;
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/tianzeng/p/10054699.html