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

后端 未结 6 1691
滥情空心
滥情空心 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:42

    This uses a divide-and-conquer approach (similar to binary search):

    1. Find the maximum of the vector.
    2. All elements to its left are accepted, whereas the maximum itself is rejected.
    3. For those elements to the right of the maximum, apply step 1.

    Although I haven't done a careful analysis, I think average complexity is O(n), or at most O(n log n). Memory is O(n).

    The result is a logical vector ind that contains true for accepted elements and false for rejected elements. The final result would be x(ind).

    x = [3 4 3 5 6 3 4 1];
    n = numel(x);
    ind = false(1,n); %// intiallization
    s = 1; %// starting index of the part of x that remains to be analyzed
    while s <= n %// if s > n we have finished
        [~, m] = max(x(s:end)); %// index of maximum within remaining part of x
        ind(s:s-2+m) = true; %// elements to its left are accepted
        s = s+m; %// update start of remaining part
    end
    

    Running time could be reduced a little by changing the while condition to while s < n, because the last element is always rejected.

提交回复
热议问题