码迷,mamicode.com
首页 > 其他好文 > 详细

949. Largest Time for Given Digits

时间:2018-12-02 20:12:11      阅读:198      评论:0      收藏:0      [点我收藏+]

标签:过滤   vector   tin   more   public   inpu   start   ace   str   

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

 

949. Largest Time for Given Digits

标签:过滤   vector   tin   more   public   inpu   start   ace   str   

原文地址:https://www.cnblogs.com/tianzeng/p/10054699.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!