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排序,这样才能得到全部的排列组合。