题解 | #牛奶供应问题# Python3
牛奶供应问题
https://www.nowcoder.com/practice/8c66c9b7deea496193e609b70f39783d
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
#
# @param taskDurations int整型一维数组
# @param capacity int整型
# @return int整型
#
class Solution:
def animalTaskScheduler(self, taskDurations: List[int], capacity: int) -> int:
# sortedTasks = sorted(taskDurations, reverse=True) # 按执行时间从大到小排序
slots = [0] * capacity # 创建一个长度为容量的时间槽数组
for task in taskDurations:
minSlotIndex = slots.index(min(slots)) # 找到时间槽中时间最小的槽索引
slots[minSlotIndex] += task # 将任务分配给时间槽,并更新时间
return max(slots) # 返回时间槽中最大的时间作为总执行时间
使用贪心算法来解决这个问题。
然后创建一个长度为容量的数组,表示每个时间槽的任务执行时间。接着,依次将任务分配给时间槽,并将该时间槽的时间增加当前任务的执行时间。最后,找出时间槽中最大的时间作为总执行时间。
最后说一句:竟然不需要将任务按照执行时间从大到小进行排序?个人觉得题意有问题
查看16道真题和解析