我有输入数组A
A[0], A[1], ... , A[N-1]
我想要函数Max(T,A)返回B代表A在大小T的先前移动窗口上的最大值,其中
B[i+T] = Max(A[i], A[i+T])
通过使用最大堆来跟踪当前移动窗口A [i]到A [i + T]的最大值,该算法会产生O(N log(T))最坏的情况。
我想知道有没有更好的算法?也许是O(N)算法
使用Deque数据结构可以实现O(N)。它包含对(值;索引)。
at every step: if (!Deque.Empty) and (Deque.Head.Index <= CurrentIndex - T) then Deque.ExtractHead; //Head is too old, it is leaving the window while (!Deque.Empty) and (Deque.Tail.Value > CurrentValue) do Deque.ExtractTail; //remove elements that have no chance to become minimum in the window Deque.AddTail(CurrentValue, CurrentIndex); CurrentMin = Deque.Head.Value //Head value is minimum in the current window