[关闭]
@Yano 2019-01-13T08:50:37.000000Z 字数 1046 阅读 1394

LeetCode 949 Largest Time for Given Digits

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

代码

这道题本质上是求一个数组的全排列,然后判断是否符合时间的格式。

  1. public String largestTimeFromDigits(int[] A) {
  2. int[] ans = new int[]{-1};
  3. timeDfs(A, ans, 0, 0, new boolean[A.length]);
  4. if (ans[0] == -1) {
  5. return "";
  6. }
  7. return getRes(ans[0]);
  8. }
  9. private String getRes(int time) {
  10. int hour = time / 100;
  11. int minute = time % 100;
  12. return (hour < 10 ? "0" + hour : hour) + ":" + (minute < 10 ? "0" + minute : minute);
  13. }
  14. private void timeDfs(int[] A, int[] ans, int num, int count, boolean[] used) {
  15. if (count == A.length) {
  16. ans[0] = Math.max(ans[0], num);
  17. return;
  18. }
  19. for (int i = 0; i < A.length; i++) {
  20. if (!used[i]) {
  21. int cal = num * 10 + A[i];
  22. if (count == 1 && (cal < 0 || cal >= 24)) {
  23. continue;
  24. }
  25. if (count == 3 && (cal % 100 < 0 || cal % 100 >= 60)) {
  26. continue;
  27. }
  28. used[i] = true;
  29. timeDfs(A, ans, cal, count + 1, used);
  30. used[i] = false;
  31. }
  32. }
  33. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注