LeetCode-401-Binary-Watch

43次阅读

共计 1877 个字符,预计需要花费 5 分钟才能阅读完成。

Description

A binary watch has 4 LEDs on the top which represent the hours (0-11), and the 6 LEDs on the bottom represent the minutes (0-59).

Each LED represents a zero or one, with the least significant bit on the right.

For example, the above binary watch reads “3:25”.

Given a non-negative integer n which represents the number of LEDs that are currently on, return all possible times the watch could represent.

Example:

Input: n = 1
Return: ["1:00", "2:00", "4:00", "8:00", "0:01", "0:02", "0:04", "0:08", "0:16", "0:32"]

Note:
The order of output does not matter.
The hour must not contain a leading zero, for example “01:00” is not valid, it should be “1:00”.
The minute must be consist of two digits and may contain a leading zero, for example “10:2” is not valid, it should be “10:02”.

描述

二进制手表顶部有 4 个 LED 代表小时(0-11),底部的 6 个 LED 代表分钟(0-59)。

每个 LED 代表一个 0 或 1,最低位在右侧。

例如,上面的二进制手表读取“3:25”。

给定一个非负整数 n 代表当前 LED 亮着的数量,返回所有可能的时间。

案例:

 输入: n = 1
返回: ["1:00", "2:00", "4:00", "8:00", "0:01", "0:02", "0:04", "0:08", "0:16", "0:32"]

注意事项:

输出的顺序没有要求。
小时不会以零开头,比如“01:00”是不允许的,应为“1:00”。
分钟必须由两位数组成,可能会以零开头,比如“10:2”是无效的,应为“10:02”。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/probl…
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

思路

  • 对每个位置编号(范围是 [0,9],一共 10 个位置),形成键值对;键位编号,值表盘对应的时间。
  • 其中,对分钟用 range(0,6) 进行编号;小时用 range(6,10) 进行编号;
  • 对于输入 num,使用 Python 的 combinations 模块,从 list(range(10)) 中随机选取 num 个数字;然后以这些数字为键,拿到对应的小时和分钟数,构成当前时间;对于不符合要求的时间直接丢弃;
# -*- coding: utf-8 -*-
# @Author:             何睿
# @Create Date:        2019-09-03 22:35:31
# @Last Modified by:   何睿
# @Last Modified time: 2019-09-04 08:59:55

from typing import List
from itertools import combinations


class Solution:
    def readBinaryWatch(self, num: int) -> List[str]:
        minutes = {i: 2**i for i in range(6)}
        hours = {i: 2**(i - 6) for i in range(6, 10)}
        times = map(lambda x: self.__transfer(x, minutes, hours), combinations(list(range(10)), num))
        
        return filter(lambda x: x is not None, times)

    def __transfer(self, com, minutes, hours):
        minute = sum(map(lambda x: minutes.get(x, 0), com))
        hour = sum(map(lambda x: hours.get(x, 0), com))

        return "{}:{:02d}".format(hour, minute) if hour <= 11 and minute <= 59 else None

源代码文件在 这里。
©本文首发于 何睿的博客,欢迎转载,转载需保留 文章来源,作者信息和本声明.

正文完
 0