LeetCode: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: ""

C++代码:

class Solution {
public:
    string largestTimeFromDigits(vector<int>& A) {
        sort(A.begin(),A.end());
        int max_hour=-1,max_min=-1;
        do{
            
            int hour = A[0]*10+A[1];
            int min = A[2]*10+A[3];
            
            if(hour>=24 || min >=60) continue;
            
            if(hour>max_hour){
                max_hour = hour;
                max_min =min;
            }
            else if(hour>=max_hour && min>=max_min){
                max_hour = hour;
                max_min = min;
                
            }
        }while(next_permutation(A.begin(),A.end()));
        
        string res="";
        if(max_hour == -1 || max_min==-1) return res;
        
        res.insert(res.begin(),max_min%10+'0');
        res.insert(res.begin(),max_min/10+'0');
        res.insert(res.begin(),':');
        res.insert(res.begin(),max_hour%10+'0');
        res.insert(res.begin(),max_hour/10+'0');
      
        return res;
    }
};

注意:next_permutation函数前面需要将数组A排序,这样才能得到全部的排列组合。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值