[leetcode] 949. Largest Time for Given Digits

网友投稿 439 2022-08-26

[leetcode] 949. Largest Time for Given Digits

Description

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 == 40 <= arr[i] <= 9

分析

题目的意思是:给定4个数,求能够组成的最大时间点的数。这道题我最先想到的是用递归,把所有的组合列举出来,选出合法的最大时间点就行了,遍历的时候用visited记录遍历过的点。这道题我看答案用的是暴力求解,调用了permutations函数,也可以。

代码

class Solution: def solve(self,arr,ans,visited): if(len(ans)==len(arr)): h=ans[0]*10+ans[1] s=ans[2]*10+ans[-1] if(h<24 and s<=59): if(self.max_hour str: n=len(arr) min_val=min(arr) self.max_hour=-1 self.max_sec=-1 visited=[False]*4 self.solve(arr,[],visited) if(self.max_hour==-1): return '' return "{:02d}:{:02d}".format(self.max_hour, self.max_sec)

参考文献

​​solution​​

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:销售人员必须学会的三三法则!(销售的三大原则)
下一篇:从2021年爆款案例,看2022年营销趋势!(2021营销发展趋势)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~