[Swift Weekly Contest 113]LeetCode949. 给定数字能组成的最大时间 | 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:

  1. A.length == 4
  2. 0 <= A[i] <= 9

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

最小的 24 小时制时间是 00:00,而最大的是 23:59。从 00:00 (午夜)开始算起,过得越久,时间越大。

以长度为 5 的字符串返回答案。如果不能确定有效时间,则返回空字符串。

示例 1:

输入:[1,2,3,4]
输出:"23:41"

示例 2:

输入:[5,5,5,5]
输出:""

提示:

  1. A.length == 4
  2. 0 <= A[i] <= 9

96ms 
 1 class Solution {
 2     func largestTimeFromDigits(_ A: [Int]) -> String {
 3         var f:[Int] = [Int](repeating:0,count:10)
 4         for x in A
 5         {
 6             f[x] += 1
 7         }
 8         for h in (0...23).reversed()
 9         {
10             for m in (0...59).reversed()
11             {
12                 var g:[Int] = [Int](repeating:0,count:10)
13                 var i:Int = h
14                 for j in 0..<2
15                 {
16                     g[i%10] += 1
17                     i /= 10
18                 }
19                 i = m
20                 for j in 0..<2
21                 {
22                     g[i%10] += 1
23                     i /= 10
24                 }
25                 if f == g
26                 {
27                     return String(format:"%02d:%02d", h, m)
28                 }
29             }
30         }
31         return String()
32     }
33 }

猜你喜欢

转载自www.cnblogs.com/strengthen/p/10052893.html
今日推荐