0%

LeetCode-621

题目

Snipaste_2020-12-05_11-17-24.png

结果

代码

ORIGIN版

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
class Solution {
public int leastInterval(char[] tasks, int n) {
int time = 0;
int count = 0;
// 各字母出现的次数
Map<Character, Integer> times = new HashMap<>();
for (char task : tasks) {
times.put(task, times.getOrDefault(task, 0) + 1);
}
// 各字母的技能CD时间
Map<Character, Integer> cd = new HashMap<>();
for (char key : times.keySet()) {
cd.put(key, 0);
}


while (count != tasks.length) {
boolean flag = false;
for (char key : mostElement(times)) {
// 如果技能冷却好了
if (times.get(key) > 0 && cd.get(key) == 0) {
// 放技能
time++;
times.put(key, times.get(key) - 1);
count++;
cd.put(key, n);
flag = true;
// 其他技能冷却时间-1
for (char k : times.keySet()) {
if (k != key && cd.get(k) != 0) {
cd.put(k, cd.get(k) - 1);
}
}
break;
}
}
// 无技能可放
if (!flag) {
time++;
for (char key : times.keySet()) {
if (cd.get(key) > 0) {
cd.put(key, cd.get(key) - 1);
}
}
}
}
return time;
}

private List<Character> mostElement(Map<Character, Integer> map) {
List<Character> list = new ArrayList<>(map.keySet());
// 按出现次序从大到小排列
list.sort((x, y) -> Integer.compare(map.get(y), map.get(x)));
return list;
}
}

稍加优化版

复杂度

时间复杂度:O()

空间复杂度:O()