LeetCode简单题Largest Time for Given Digits

LeetCode简单题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.

大致意思是对于任意输入的4位数,输出该4位数可以组成的时间形式,并取其中最大的一种
如 [1、2、3、4]—>23:41
[0、2、6、6 ]-----> 06:26
[5 5 5 5]------> “”(没有则返回空)

分析

本质是一道数字组合题,但对组合有约束限制,将数字转换为数字进行思考,即组合对数字(time)应该有
1、time<2400
2、time%100<60
所以第一种思路是,先对输入数组(A)进行排序,即sort(A.begin(),A.end())
排序的目的是让其能够和<2400,之后对(0,2400)进行遍历,找到4位数字排序后与sort(A)相同的数字,显然,最后一个数字是最大。

string largestTimeFromDigits2(vector<int>& A){
    // sort(A)
    sort(A.begin(),A.end());
    string answer="";
    string tmp;
    for(int t=0;t<2400;t++){	// 遍历所有<2400
        if(t%100>=60) continue; // 分钟>60跳过
        int tmp_t=t;
        vector<int>res;
        for(int i=0;i<4;i++)
        {
            res.push_back(tmp_t %10);  //pow return a float value
            tmp_t /=10;
            //tmp+=to_string()
        }
        sort(res.begin(),res.end());
        
        if(A==res){
            //string str1=to_string(tmp_t)[0]+to_string(tmp_t)[1];
            //string str2=to_string(tmp_t)[2]+to_string(tmp_t)[3];
            //string str1(to_string(tmp_p),2);
            //answer=to_string(int(t/100))+':'+to_string(t%100);
            char str[100];
            sprintf(str, "%02d:%02d", t / 100, t % 100);  // 可以为空位添加0
            answer = str;
        }
    }
    return answer;
}

第2种思路是分开考虑时间,即分别考虑小时的最大值和分钟的最大值,这里要用的STL的一个next_permutation函数,此函数可以用来遍历一个序列的所有全排列。

string largestTimeFromDigits3(vector<int>& A){
    int hours=0;
    int minute=0;
    bool answer=false;		// 用于判断有没有解
    sort(A.begin(),A.end());
    do{
        int tmp_hours=A[0]*10+A[1];	// 计算当前排列的小时
        int tmp_minute=A[2]*10+A[3]; // 计算当前排列的分钟
        if(tmp_hours<24 && tmp_hours>hours){
            if(tmp_minute<60){
                hours=tmp_hours;
                minute=tmp_minute;
                answer=true;
            }
            else ;
        }
        if(tmp_hours==hours && tmp_minute>minute && tmp_minute<60)
            minute=tmp_minute;
    }while(next_permutation(A.begin(),A.end()));
    //cout<<hours<<minute<<endl;
    string res;
    if(hours<10)
        res+='0';
    res+=to_string(hours);
    res+=':';
    if(minute<10)
        res+='0';
    res+=to_string(minute);
    return res;
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值