题目
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;