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

后端 未结 7 1751
长情又很酷
长情又很酷 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:40

    If, and only if, the source array is sorted, this can be done in linear time:

    std::unique(a, a + 5); //Returns a pointer to the new logical end of a.
    

    Otherwise you'll have to sort first, which is (99.999% of the time) n lg n.

提交回复
热议问题