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
给定一个由 4 位数字组成的数组,返回可以设置的符合 24 小时制的最大时间。
最小的 24 小时制时间是 00:00,而最大的是 23:59。从 00:00 (午夜)开始算起,过得越久,时间越大。
以长度为 5 的字符串返回答案。如果不能确定有效时间,则返回空字符串。
蓝桥杯校赛考了查不类似的题,然后不会做,是思路的问题,上午一直在做递归的题,然后下午看到这题下意识的反应要递归出全部情况,然后再设置条件得出最大的时间数,没想到直接用 for 循环,暴力大法好啊。其实这也是 leetcode 上 949 的难度为简单的题,我还是太年轻了啊。
思路:因为只有 4 个数字,可组合的形式相对而言比较少,所以直接用三个 for 循环暴力破解,在这其中的话分别设置条件使得 i,j,k 不相同,并且 i,j,k,l 数字之和不超过 6 ,因为数组下标是从 0,1,2,3 开始的,所以利用这个特性可以少用一个循环,得出 l ,这样就将数组的数全部遍历出来了,然后再根据条件进行选择,最后是将数组转换成数字进行比较,选取最大的数即可。
然后就是采用 String 的 format 方法格式化输出数字了。
代码:
public static String g(int[] a){
int ans = -1; // 存储时间转换以后的最大值
for(int i = 0;i < 4;++i){
for(int j = 0;j < 4;++j){
if(i != j)
for(int k = 0;k < 4;k++){
if(k != i && k!= j){
int l = 6-i-j-k;
int hours = a[i]*10 + a[j];
int mins = a[k]*10 + a[l];
if(hours < 24 && mins < 60){
ans = Math.max(anx,hours*60 + mins); // 将时间转换成分针进行比较
}
}
}
}
}
return ans >= 0?String.format("%02d:%02d",ans/60,ans%60);
}