您的算法非常慢,因为如果有(…)必须在第一次迭代中检查n个项目,则在第二次迭代中检查n-1个项目,直到在上一次迭代中检查单个项目.因此,它必须大致进行n ^ 2/2比较,因此其运行时间是二次函数,作为输入向量的长度的函数!
在时间和记忆中是线性的一种解决方案可能是首先计算从该点到最后的最大值的向量,其可以在一次向后传递中计算
(你可以称之为累积最大值,即cannot be vectorized).之后,将此向量直接与x(未测试)进行比较:
% calculate vector mx for which mx(i) = max(x(i:end))
mx = zeros(size(x));
mx(end) = x(end);
for i = length(x)-1:-1:1 % iterate backwards
mx(i) = max(x(i), mx(i+1));
end
for i = 1:length(x) - 1
if mx(i) > x(i)
do_such_and_such(i);
end
end
如果您不关心执行do_such_and_such的顺序,这些for循环甚至可以像这样组合:
mx = x(end);
for i = length(x)-1:-1:1 % iterate backwards
if x(i) < mx
do_such_and_such(i);
end
mx = max(x(i), mx); % maximum of x(i:end)
end