How does one remove duplicate elements in place in an array in O(n) in C or C++?

后端 未结 7 1733
长情又很酷
长情又很酷 2020-12-16 21:43

Is there any method to remove the duplicate elements in an array in place in C/C++ in O(n)? Suppose elements are a[5]={1,2,2,3,4} then resulting array should c

7条回答
  •  借酒劲吻你
    2020-12-16 22:34

    The canonical implementation of the unique() algorithm looks like something similar to the following:

    template
    Fwd unique(Fwd first, Fwd last)
    {
        if( first == last ) return first;
        Fwd result = first;
        while( ++first != last ) {
            if( !(*result == *first) )
                *(++result) = *first;
        }
        return ++result;
    }
    

    This algorithm takes a range of sorted elements. If the range is not sorted, sort it before invoking the algorithm. The algorithm will run in-place, and return an iterator pointing to one-past-the-last-element of the unique'd sequence.

    If you can't sort the elements then you've cornered yourself and you have no other choice but to use for the task an algorithm with runtime performance worse than O(n).

    This algorithm runs in O(n) runtime. That's big-oh of n, worst case in all cases, not amortized time. It uses O(1) space.

提交回复
热议问题