How to keep only duplicates efficiently?

后端 未结 10 744
闹比i
闹比i 2021-01-04 06:14

Given an STL vector, output only the duplicates in sorted order, e.g.,

INPUT : { 4, 4, 1, 2, 3, 2, 3 }
OUTPUT: { 2, 3, 4 }

The algorithm is

10条回答
  •  温柔的废话
    2021-01-04 06:43

    I miserably failed with my first attempt, assuming that std::unique moves all the duplicates to the end of the range (it doesn't). Oops. Here's another attempt:

    Here is an implementation of not_unique. It removes any elements that appear only once in the sorted range and duplicates of any elements that appear more than once. The resulting range is therefore the unique list of elements that appear more than once.

    The function has linear complexity and does a single pass over the range (std::unique has linear complexity). It must meet the requirements of a forward iterator. The end of the resulting range is returned.

    template 
    It not_unique(It first, It last)
    {
        if (first == last) { return last; }
    
        It new_last = first;
        for (It current = first, next = ++first; next != last; ++current, ++next)
        {
            if (*current == *next)
            {
                if (current == new_last)
                {
                    ++new_last;
                }
                else
                {
                    *new_last++ = *current;
                    while (next != last && *current == *next)
                    {
                        ++current;
                        ++next;
                    }
                    if (next == last)
                        return new_last;
                }
            }
        }
        return new_last;
    }
    

提交回复
热议问题