How to keep only duplicates efficiently?

后端 未结 10 743
闹比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:49

    You can even use mismatch, for extra points!
    Btw: nice exercise.

    template
    /** Moves duplicates to front, returning end of duplicates range.
     *  Use a sorted range as input. */
    TIter Duplicates(TIter begin, TIter end) {
        TIter dup = begin;
        for (TIter it = begin; it != end; ++it) {
            TIter next = it;
            ++next;
            TIter const miss = std::mismatch(next, end, it).second;
            if (miss != it) {
                *dup++ = *miss;
                it = miss;
            }
        }
        return dup;
    }
    

提交回复
热议问题