在Python中查找前k个观看最多的展示的总看完时间
假设我们有一个名为shows的字符串列表和一个名为durations的整数列表,还有另一个值k。 这里shows[i]和durations[i]表示第i个人观看的展示和其持续时间,我们必须找到k个最受欢迎的展示的总观看时间。
因此,如果输入如下:shows = [“The BGT”, “Jack jumper”, “The BGT”, “Jokers Company”, “Music magic”] durations = [10, 8, 10, 18, 9] k = 2,则输出将为38,因为前两个观看最多的展示是”Jokers Company”和”The BGT”,总持续时间为18和10 + 10 = 20。
要解决此问题,我们将遵循以下步骤:
- 如果shows为空或durations为空或k为0,则
- 返回0
- d := 一个空字典
-
对于在0到shows大小之间的i,执行以下操作:
- d[shows[i]] := d[shows[i]] + durations[i]
- l := 一个新列表
-
对于每个i在d中,执行以下操作:
- 将d[i]插入l的末尾
- 对列表l进行反向排序
-
i := 0
-
answer := 0
-
当i < k时,执行以下操作:
- answer := answer + l[i]
-
i := i + 1
-
返回结果answer
示例
以下是更好的理解实现
from collections import defaultdict
def solve(shows, durations, k):
if not shows or not durations or not k:
return 0
d = defaultdict(int)
for i in range(len(shows)):
d[shows[i]] += durations[i]
l = []
for i in d:
l.append(d[i])
l.sort(reverse=True)
i = 0
answer = 0
while i < k:
answer += l[i]
i += 1
return answer
shows = ["The BGT", "Jack jumper", "The BGT", "Jokers Company",
"Music magic"]
durations = [10, 8, 10, 18, 9]
k = 2
print(solve(shows, durations, k))
输入
["The BGT", "Jack jumper", "The BGT", "Jokers Company", "Music magic"], [10, 8, 10, 18, 9], 2
输出
38