发现小于某些元件在其右侧的每个元素 [英] Find each element that is less than some element to its right

查看:120
本文介绍了发现小于某些元件在其右侧的每个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要找到是后认为来多种元素的小于一的载体的元素。这很容易在一个循环做:

  X = some_vector_values​​;
对于m = 1:长度(x)的
  如果(任何(X(m + 1个:结束)X的催化剂(M))
    do_such_and_such;
  结束
结束

但速度是我的命。我抓我的头试图想出一个有效的解决方法,但我来了空白。数组长度可以是成千上万的顺序,我需要为许多不同的阵列做到这一点。


解决方案

您的算法是如此之慢,因为(如果有的话......)必须检查<$ C $ ç> N 上的第一个迭代的项目,那么第二次迭代N-1 项目......直到最后一次迭代检查单个项目。全部测试它因此具有大致做 N ^ 2/2 比较,所以它的运行时间是二次作为输入矢量的长度的函数<!/ P>

的一个解决方案是线性的时间和内存可能是首先计算与来自该点的最大直到结束,它可以在一个向后传来计算一个矢量
(你可以称这是一个颠倒累计最高,这不能矢量)。在此之后,这个载体是直接与 X (未经测试):

 %计算矢量的MX其中MX(I)= MAX(X(I:结束))
的mx =零(大小(X));
MX(完)= X(完)
对于i =长度(x)的-1:-1:1%迭代向后
    的mx(ⅰ)= MAX(X(i)中,MX第(i + 1));
结束对于i = 1:长度(X) - 1
    如果MX(I)GT; X(ⅰ)
        do_such_and_such(ⅰ);
    结束
结束

如果你不关心在 do_such_and_such 执行时,这些for循环,甚至可以结合起来,像这样的命令:

  MX = X(完)
对于i =长度(x)的-1:-1:1%迭代向后
    如果x(I)所述; MX
        do_such_and_such(ⅰ);
    结束
    的mx = MAX(X(i)中,MX); %最大X的(我:完)
结束

I need to find elements of a vector that are less than one of more elements that come after it. It's easy to do in a loop:

x = some_vector_values;
for m = 1 : length(x)
  if( any( x(m+1:end) > x(m) )
    do_such_and_such;
  end
end

but the speed is killing me. I'm scratching my head trying to come up with an efficient work-around but am coming up blank. The array length can be on the order of thousands and I need to do this for many different arrays.

解决方案

Your algorithm is so slow since if any(...)has to check n items on the first iteration, then n-1 items on the second iteration ... until checking a single item in the last iteration. Overal it thus has to do roughly n^2/2 comparisons, so its running time is quadratic as a function of the length of the input vector!

One solution that is linear in time and memory might be to first calculate a vector with the maximum from that point until the end, which can be calculated in one backwards pass (you could call this a reversed cumulative maximum, which cannot be vectorized). After this, this vector is compared directly to x (untested):

% 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

In case you don't care about the order in which do_such_and_such is executed, these for loops can even be combined like so:

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

这篇关于发现小于某些元件在其右侧的每个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆