[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 == 4
  • 0 <= 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<h):
                    self.max_hour=h
                    self.max_sec=s
                elif(self.max_hour==h and self.max_sec<s):
                    self.max_sec=s
            return
                    
        for i in range(len(arr)):
            if(visited[i]==False):
                visited[i]=True
                ans.append(arr[i])
                self.solve(arr,ans,visited)
                ans.pop()
                visited[i]=False
                
            
    def largestTimeFromDigits(self, arr: List[int]) -> 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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

农民小飞侠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值