Largest Time for Given Digits (E)
题目
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时制的时间。
思路
可以直接回溯法解决。每一位上都有一个值的范围,从最大值往前遍历寻找可能的组合。
或者直接对小时23-0和对分钟59-0进行二重循环遍历。
代码实现
Java
回溯法
class Solution {
public String largestTimeFromDigits(int[] A) {
int[] digits = new int[10];
for (int num : A) {
digits[num]++;
}
return generate(digits, 0, "");
}
private String generate(int[] digits, int index, String s) {
if (index == 5) {
return s;
}
if (index == 2) {
return generate(digits, index + 1, s + ":");
}
int max = index == 0 ? 2 : index == 1 ? (s.charAt(0) == '2' ? 3 : 9) : index == 3 ? 5 : 9;
for (int i = max; i >= 0; i--) {
if (digits[i] > 0) {
digits[i]--;
String t = generate(digits, index + 1, s + i);
if (!t.isEmpty()) {
return t;
} else {
digits[i]++;
}
}
}
return "";
}
}
二重循环
class Solution {
public String largestTimeFromDigits(int[] A) {
Arrays.sort(A);
for (int i = 23; i >= 0; i--) {
for (int j = 59; j >= 0; j--) {
int a = i < 10 ? 0 : i / 10;
int b = i % 10;
int c = j < 10 ? 0 : j / 10;
int d = j % 10;
int[] B = { a, b, c, d };
Arrays.sort(B);
boolean valid = true;
for (int k = 0; k < 4; k++) {
if (A[k] != B[k]) {
valid = false;
break;
}
}
if (valid) {
return "" + a + b + ":" + c + d;
}
}
}
return "";
}
}