Optimization 此面试问题的最佳解决方案

Optimization 此面试问题的最佳解决方案,optimization,Optimization,谁能提供具有时间复杂性的最佳解决方案?非常感谢 确定运行预定视频流所需的带宽。 可以有10个成千上万的流,并且所有的调度数据在开始时都可用。 没有流运行时可能存在时间间隔 投入 int startTime; //start time for the stream int duration; //how long the stream runs int bandwidth; // consumed bandwidth from start to end 输出: list[int] tot

谁能提供具有时间复杂性的最佳解决方案?非常感谢

确定运行预定视频流所需的带宽。
可以有10个成千上万的流,并且所有的调度数据在开始时都可用。
没有流运行时可能存在时间间隔

投入

int startTime; //start time for the stream  
int duration; //how long the stream runs  
int bandwidth; // consumed bandwidth from start to end
输出:

list[int] totalBW; // bandwidth needed at every time instant
示例
输入(列表可能未排序)

输出

[10, 20, 30]
解释

At time 0: only the first element needs bandwidth 10 =>  [10, ...]
At time 1: first two elements need bandwidth 10 + 10 => [10, 20, ...]
At time 2: the second and third element need bandwidth 10 + 20 => [10, 20, 30]
使用python的暴力方法:

def solution(streams):
    _max = max(streams, key=lambda x: (x[0]+x[1]))
    _max_time = _max[0] + _max[1] 
    res = [0] * _max_time
        
    for s, d, bw in streams:
        for i in range(d):
            res[s+i] += bw
    return res
有没有更有效的方法

有没有更有效的方法

第一步是将原始数据转换为一组“at time=T,带宽变化按N”事件,按时间顺序排序,并通过合并同时发生的事件来简化

例如,如果输入为
[[0,2,10],[1,2,10],[2,1,20]
,则将其分为:

** [ [0,2,10] **
    At 0, bandwidth += 10 
    At 2, bandwidth += -10

** [1,2,10] **
    At 1, bandwidth += 10
    At 3, bandwidth += -10

** [2,1,20] **
    At 2, bandwidth += 20
    At 3, bandwidth += -20
…然后进行排序和简化(合并同时发生的事件-例如,
带宽+=-10,带宽+=20
成为单个
带宽+=10
)以获得:

从这里,只需从排序列表生成最终数组:

 10, 20, 30, 0
为了理解为什么这更有效,想象一下如果以更高的精度跟踪时间(例如,可能是毫秒而不是秒),而输入是
[[02000,10],[10002000,10],[20001000,20]
会发生什么。在我的方法中,生成最终数组将成为一个包含4次迭代的外循环和一个内部循环,可以是高度优化的
memset()
(C)或
rep stosd
(80x86汇编)或
np.full()
(带numpython的Python);对于您的方法,外循环需要30000次迭代,其中内循环浪费大量时间重复线性搜索(对于外循环的大多数迭代)以找到与前一次外循环迭代相同的答案

At 0, bandwidth += 10 
At 1, bandwidth += 10
At 2, bandwidth += 10
At 3, bandwidth += -30
 10, 20, 30, 0