@Yano
2019-01-13T16:50:37.000000Z
字数 1046
阅读 1523
LeetCode
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
这道题本质上是求一个数组的全排列,然后判断是否符合时间的格式。
public String largestTimeFromDigits(int[] A) {
int[] ans = new int[]{-1};
timeDfs(A, ans, 0, 0, new boolean[A.length]);
if (ans[0] == -1) {
return "";
}
return getRes(ans[0]);
}
private String getRes(int time) {
int hour = time / 100;
int minute = time % 100;
return (hour < 10 ? "0" + hour : hour) + ":" + (minute < 10 ? "0" + minute : minute);
}
private void timeDfs(int[] A, int[] ans, int num, int count, boolean[] used) {
if (count == A.length) {
ans[0] = Math.max(ans[0], num);
return;
}
for (int i = 0; i < A.length; i++) {
if (!used[i]) {
int cal = num * 10 + A[i];
if (count == 1 && (cal < 0 || cal >= 24)) {
continue;
}
if (count == 3 && (cal % 100 < 0 || cal % 100 >= 60)) {
continue;
}
used[i] = true;
timeDfs(A, ans, cal, count + 1, used);
used[i] = false;
}
}
}