Find each element that is less than some element to its right

后端 未结 6 1658
滥情空心
滥情空心 2021-01-12 03:05

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         


        
6条回答
  •  终归单人心
    2021-01-12 03:59

    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
    

提交回复
热议问题