leetcode-401-easy
Binary Watch
A binary watch has 4 LEDs on the top to represent the hours (0-11), and 6 LEDs on the bottom to represent the minutes (0-59). Each LED represents a zero or one, with the least significant bit on the right.
For example, the below binary watch reads "4:51".
Given an integer turnedOn which represents the number of LEDs that are currently on (ignoring the PM), return all possible times the watch could represent. You may return the answer in any order.
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".
Example 1:
Input: turnedOn = 1
Output: ["0:01","0:02","0:04","0:08","0:16","0:32","1:00","2:00","4:00","8:00"]
Example 2:
Input: turnedOn = 9
Output: []
Constraints:
0 <= turnedOn <= 10
思路一:左右两边,左边 [0-11],右边 [0-59],分别统计两边的 bit 位数。 turnedOn = left + right,嵌套遍历即可
private static final Map<Integer, List<Integer>> leftMap = countMap(12);
private static final Map<Integer, List<Integer>> rightMap = countMap(60);
public List<String> readBinaryWatch(int turnedOn) {
List<String> list = new ArrayList<>();
for (int i = 0; i <= turnedOn; i++) {
if (leftMap.containsKey(i) && rightMap.containsKey(turnedOn - i)) {
for (Integer x : leftMap.get(i)) {
for (Integer y : rightMap.get(turnedOn - i)) {
list.add(x + ":" + ((y < 10) ? "0" : "") + y);
}
}
}
}
return list;
}
private static Map<Integer, List<Integer>> countMap(int limit) {
Map<Integer, List<Integer>> map = new HashMap<>();
for (int i = 0; i < limit; i++) {
int finalI = i;
map.compute(Integer.bitCount(i), (k, v) -> {
if (v == null) {
v = new ArrayList<>();
v.add(finalI);
} else {
v.add(finalI);
}
return v;
});
}
return map;
}
思路二:看了一下题解,有更好的解法,由于总共就 10 个 bit 位,所以攻击 2**20=1024 种情况,判断每种情况是否合法,即可求解

浙公网安备 33010602011771号