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
题目理解:
给定四个数字,求其能够组成的最大的合法二十四小时制时间
解题思路:
遍历一天中全部24*60个时间,从大往小遍历,如果这个时间中的数字与给出的数字相同,那么返回它
class Solution {
public String largestTimeFromDigits(int[] A) {
for(int hour = 23; hour > -1; hour--){
for(int minute = 59; minute > -1; minute--){
int[] record = new int[10];
for(int num : A)
record[num]++;
record[hour % 10]--;
record[hour / 10]--;
record[minute % 10]--;
record[minute / 10]--;
boolean flag = true;
for(int num : record)
if(num != 0)
flag = false;
if(flag){
String h = hour + "", m = minute + "";
if(hour < 10)
h = "0" + h;
if(minute < 10)
m = "0" + m;
return h + ":" + m;
}
}
}
return "";
}
}