LeetCode刷题之949. 给定数字能组成的最大时间
我不知道将去向何方,但我已在路上! |
---|
时光匆匆,虽未曾谋面,却相遇于斯,实在是莫大的缘分,感谢您的到访 ! |
- 题目:
给定一个由 4 位数字组成的数组,返回可以设置的符合 24 小时制的最大时间。最小的 24 小时制时间是00:00,而最大的是23:59。从 00:00 (午夜)开始算起,过得越久,时间越大。以长度为 5 的字符串返回答案。如果不能确定有效时间,则返回空字符串。 - 示例:
示例 1:
输入:[1,2,3,4]
输出:"23:41"
示例 2:
输入:[5,5,5,5]
输出:""
A.length == 4
0 <= A[i] <= 9
class Solution:
def largestTimeFromDigits(self, A: List[int]) -> str:
import itertools
A.sort()
a = list(itertools.permutations(A))
result = []
for zuhe in a:
if zuhe[0] == 2 and zuhe[1] <= 3 and zuhe[2] <= 5:
result.append(zuhe)
continue
if zuhe[0] < 2 and zuhe[2] <= 5:
result.append(zuhe)
if result == []:
return("")
return(str(result[-1][0]) + str(result[-1][1]) + ':' + str(result[-1][2]) + str(result[-1][3]))
- 算法说明:
先将A
中的元素排序,然后得到A
中元素的全排列,用for
循环进行筛选,如果第一位等于2
,第二位不大于3
,第三位不大于5
,将该元素附加到列表result
中;如果第一位小于2
,第二位没要求,第三位不大于5
,将该元素附加到列表result
中;如果result
为空,说明不符合时间格式;由于A
已经排过序,所以返回A
的最后一个元素(用字符串格式)。