LeetCode 949 Largest Time for Given Digits 題目描述 代碼

題目描述

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;
        }
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章