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:
A.length == 4
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;
}
}
};