Skip to content

Commit 64c8fc4

Browse files
aQuaaQua
aQua
authored and
aQua
committed
621 finish
1 parent 6403d1f commit 64c8fc4

File tree

2 files changed

+48
-31
lines changed

2 files changed

+48
-31
lines changed
Lines changed: 38 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -1,43 +1,50 @@
11
package Problem0621
22

3-
import (
4-
"sort"
5-
)
6-
73
func leastInterval(tasks []byte, n int) int {
8-
rec := make([]int, 26)
9-
for _, b := range tasks {
10-
rec[b-'A']++
4+
if n == 0 {
5+
return len(tasks)
116
}
12-
sort.Ints(rec)
13-
14-
res := 0
15-
intervals := 0
16-
idx := 0
17-
for len(rec) > 0 {
18-
if intervals > 0 {
19-
res += intervals
20-
}
217

22-
// 新周期
23-
intervals = n + 1
8+
rec := [26]int{}
9+
for _, c := range tasks {
10+
rec[c-'A']++
11+
}
2412

25-
idx = len(rec) - 1
26-
for intervals > 0 && idx >= 0 && rec[idx] > 0 {
27-
rec[idx]--
28-
intervals--
29-
idx--
30-
res++
13+
// 找到最多的任务数
14+
most := 0
15+
for _, num := range rec {
16+
if most < num {
17+
most = num
3118
}
19+
}
3220

33-
sort.Ints(rec)
34-
idx = len(rec) - 1
35-
for idx >= 0 && rec[idx] > 0 {
36-
idx--
37-
}
21+
// 整个过程,至少有 idles 个空档需要被填充
22+
idles := (most - 1) * (n + 1)
23+
24+
// 使用每一个 task 去填充 idles
25+
for _, num := range rec {
26+
// 可以假想 idles+1 个空档,被 most 的 task 等间距n填充后,
27+
// 分割成了 most-1 个包含连续 n 个空档的区间
28+
// 然后,同样的任务,只能往每个区间中去填充。
29+
idles -= min(most-1, num)
30+
// 由于是使用 most 做的分割
31+
// 如果最后的 idles < 0 只能说明
32+
// len(tasks) > (most - 1) * (n + 1)+1
33+
}
34+
35+
return len(tasks) + max(0, idles)
36+
}
3837

39-
rec = rec[idx+1:]
38+
func min(a, b int) int {
39+
if a < b {
40+
return a
4041
}
42+
return b
43+
}
4144

42-
return res
45+
func max(a, b int) int {
46+
if a > b {
47+
return a
48+
}
49+
return b
4350
}

Algorithms/0621.task-scheduler/task-scheduler_test.go

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,16 @@ func Test_Problem0621(t *testing.T) {
4848
},
4949
},
5050

51+
question{
52+
para{
53+
[]byte{'A', 'A', 'A', 'A', 'A', 'A', 'B', 'B', 'B', 'C', 'C', 'C'},
54+
0,
55+
},
56+
ans{
57+
12,
58+
},
59+
},
60+
5161
question{
5262
para{
5363
[]byte{'A', 'A', 'A', 'A', 'A', 'A', 'B', 'B', 'B', 'C', 'C', 'C'},

0 commit comments

Comments
 (0)