[LeetCode] 949. Largest Time for Given Digits

Given an array arr of 4 digits, find the latest 24-hour time that can be made using each digit exactly once.

24-hour times are formatted as "HH:MM", where HH is between 00 and 23, and MM is between 00 and 59. The earliest 24-hour time is 00:00, and the latest is 23:59.

Return the latest 24-hour time in "HH:MM" format.  If no valid time can be made, return an empty string.

Example 1:

Input: A = [1,2,3,4]
Output: "23:41"
Explanation: The valid 24-hour times are "12:34", "12:43", "13:24", "13:42", "14:23", "14:32", "21:34", "21:43", "23:14", and "23:41". Of these times, "23:41" is the latest.

Example 2:

Input: A = [5,5,5,5]
Output: ""
Explanation: There are no valid 24-hour times as "55:55" is not valid.

Example 3:

Input: A = [0,0,0,0]
Output: "00:00"

Example 4:

Input: A = [0,0,1,0]
Output: "10:00"

Constraints:

  • arr.length == 4
  • 0 <= arr[i] <= 9

给定数字能组成的最大时间。

给定一个由 4 位数字组成的数组,返回可以设置的符合 24 小时制的最大时间。

24 小时格式为 "HH:MM" ,其中 HH 在 00 到 23 之间,MM 在 00 到 59 之间。最小的 24 小时制时间是 00:00 ,而最大的是 23:59 。从 00:00 (午夜)开始算起,过得越久,时间越大。

以长度为 5 的字符串,按 "HH:MM" 格式返回答案。如果不能确定有效时间,则返回空字符串。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/largest-time-for-given-digits
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

这道题不涉及算法,但是对于如何判断一个由字符组成的时间是否合法可能是有示范作用的。给的input是一个长度为4的数组,表示时间的4个digit,那么即使是暴力解,出现的可能性也是有限的。我们遍历input数组,试图把每一个数字 A[i] 在时间的每一个digit上都摆一次,试试看是否能组成一个最大的时间。6 - i - j - k的意思是,因为最后无论组成什么时间,四个digit的下标分别是0, 1, 2, 3,他们的和是6,所以当我确定了前三个digit的下标之后,第四个下标就是这样产生的。

时间O(1) - 因为只有24种组合

空间O(1)

Java实现

 1 class Solution {
 2     public String largestTimeFromDigits(int[] A) {
 3         String res = "";
 4         for (int i = 0; i < 4; i++) {
 5             for (int j = 0; j < 4; j++) {
 6                 for (int k = 0; k < 4; k++) {
 7                     if (i == j || i == k || j == k) {
 8                         continue;
 9                     }
10                     String h = "" + A[i] + A[j];
11                     String m = "" + A[k] + A[6 - i - j - k];
12                     String t = h + ":" + m;
13                     if (h.compareTo("24") < 0 && m.compareTo("60") < 0 && res.compareTo(t) < 0) {
14                         res = t;
15                     }
16                 }
17             }
18         }
19         return res;
20     }
21 }

 

LeetCode 题目总结 

posted @ 2021-01-27 01:23  CNoodle  阅读(148)  评论(0编辑  收藏  举报