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
class Solution {
public:
    bool flag(vector<int>& A){   //这里将动态数组传递而不是传n再分割  节省时间
        if(A[0]==2){
            if(A[1]>=0&&A[1]<=3&&A[2]>=0&&A[2]<=5)
                return true;
            else
                return false; 
        }else if(A[0]<2){
            if(A[2]>=0&&A[2]<6)
                return true;
            else 
                return false;
        }else
             return false;
    }
    string largestTimeFromDigits(vector<int>& A) {
        int n,maxx=-1;
        int a,b,c,d;
        string s;
        sort(A.begin(),A.end());   //next_permutation 从当前排列开始取后面的排列,要想遍历所有的排列,需要先对数组排序
        do{
            n=A[0]*1000+A[1]*100+A[2]*10+A[3];
            if(flag(A)==1){
                if(n>maxx){
                    maxx=n;
                    a=A[0];
                    b=A[1];
                    c=A[2];
                    d=A[3];
                }
            }
        }while(next_permutation(A.begin(),A.end()));
        if(maxx==-1)
            return s;
        else{
            s=to_string(a)+to_string(b)+":"+to_string(c)+to_string(d);  //to_string(int)将int转化为string型
            return s;
        }
    }
};

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值