LC 401. 二进制手表

题目描述

这是 LeetCode 上的 401. 二进制手表 ,难度为 简单

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

每个 LED 代表一个 01,最低位在右侧。

例如,下面的二进制手表读取 "3:25"

给你一个整数 turnedOn,表示当前亮着的 LED 的数量,返回二进制手表可以表示的所有可能时间。你可以按任意顺序返回答案。

小时不会以零开头:

例如,"01:00" 是无效的时间,正确的写法应该是 "1:00"

分钟必须由两位数组成,可能会以零开头:

例如,"10:2" 是无效的时间,正确的写法应该是 "10:02"

示例 1:

1
2
3
输入:turnedOn = 1

输出:["0:01","0:02","0:04","0:08","0:16","0:32","1:00","2:00","4:00","8:00"]

示例 2:
1
2
3
输入:turnedOn = 9

输出:[]

提示:

  • $0 <= turnedOn <= 10$

打表

具体的,我们可以创建一个 静态数据结构 来存储打表信息(需确保全局唯一,即使存在多组测试数据只生成一次打表数据)。

然后在返回数据的时候直接 $O(1)$ 查表返回。

PS. 如果打表逻辑计算量接近 $10^7$ 上限,可以考虑放到本地去做,这里数据量较少,直接放到 static 代码块去做即可。

Java 代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Solution {    
// 打表逻辑,也可以放到本地做
// 注意使用 static 修饰,确保打表数据只会被生成一次
static Map<Integer, List<String>> map = new HashMap<>();
static {
for (int h = 0; h <= 11; h++) {
for (int m = 0; m <= 59; m++) {
int tot = getCnt(h) + getCnt(m);
List<String> list = map.getOrDefault(tot, new ArrayList<String>());
list.add(h + ":" + (m <= 9 ? "0" + m : m));
map.put(tot, list);
}
}
}
static int getCnt(int x) {
int ans = 0;
for (int i = x; i > 0; i -= lowbit(i)) ans++;
return ans;
}
static int lowbit(int x) {
return x & -x;
}
public List<String> readBinaryWatch(int t) {
return map.getOrDefault(t, new ArrayList<>());
}
}

C++ 代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class Solution {
public:
static unordered_map<int,vector<string>> mp;
static int cnt;
static int getCnt(int x) {
int ans = 0;
for (int i = x; i > 0; i -= lowbit(i)) ans++;
return ans;
}
static int lowbit(int x) {
return x & -x;
}
static void PreTable(){
cnt++;
for (int h = 0; h <= 11; h++) {
for (int m = 0; m <= 59; m++) {
int tot = getCnt(h) + getCnt(m);
char buffer[6];
sprintf(buffer,"%d:%02d",h,m);
mp[tot].push_back(buffer);
}
}
}
vector<string> readBinaryWatch(int turnedOn) {
if(cnt == 1) PreTable();
return mp[turnedOn];
}
};

int Solution::cnt = 1;
unordered_map<int,vector<string>> Solution::mp = {};

Python 代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
def getCnt(x):
ans, i = 0, x
while i > 0:
ans += 1
i -= lowbit(i)
return ans

def lowbit(x):
return x & -x

mp = defaultdict(list)
for h in range(12):
for m in range(60):
tot = getCnt(h) + getCnt(m)
mp[tot].append(f"{h}:{m:02d}")

class Solution:
def readBinaryWatch(self, turnedOn: int) -> List[str]:
return mp[turnedOn]

  • 时间复杂度:$O(1)$
  • 空间复杂度:$O(n)$

最后

这是我们「刷穿 LeetCode」系列文章的第 No.401 篇,系列开始于 2021/01/01,截止于起始日 LeetCode 上共有 1916 道题目,部分是有锁题,我们将先把所有不带锁的题目刷完。

在这个系列文章里面,除了讲解解题思路以外,还会尽可能给出最为简洁的代码。如果涉及通解还会相应的代码模板。

为了方便各位同学能够电脑上进行调试和提交代码,我建立了相关的仓库:https://github.com/SharingSource/LogicStack-LeetCode

在仓库地址里,你可以看到系列文章的题解链接、系列文章的相应代码、LeetCode 原题链接和其他优选题解。


本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!