LeetCode 949 Largest Time for Given Digits (Python)

Posted by 小明MaxMing on September 1, 2020

题目

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.

解题思路

枚举四个数的排列,找到符合条件的最大时间

代码

class Solution:
    def largestTimeFromDigits(self, A: List[int]) -> str:
        res = -1
        for h1, h2, m1, m2 in itertools.permutations(A):
            hour = h1 * 10 + h2
            minute = m1 * 10 + m2
            if hour < 24 and minute < 60:
                time = hour * 60 + minute
                res = max(res, time)
        return "%02d:%02d" % divmod(res, 60) if res >= 0 else ""

视频讲解 YouTube<--欢迎点击订阅

视频讲解 bilibili<--欢迎点击订阅