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

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

    I'm going to suggest a variation on Borealids answer, but I'll point out up front that it's cheating. Basically, it only works assuming some severe constraints on the values in the array - e.g. that all keys are 32-bit integers.

    Instead of a hash table, the idea is to use a bitvector. This is an O(1) memory requirement which should in theory keep Rahul happy (but won't). With the 32-bit integers, the bitvector will require 512MB (ie 2**32 bits) - assuming 8-bit bytes, as some pedant may point out.

    As Borealid should point out, this is a hashtable - just using a trivial hash function. This does guarantee that there won't be any collisions. The only way there could be a collision is by having the same value in the input array twice - but since the whole point is to ignore the second and later occurences, this doesn't matter.

    Pseudocode for completeness...

    src = dest = input.begin ();
    while (src != input.end ())
    {
      if (!bitvector [*src])
      {
        bitvector [*src] = true;
        *dest = *src; dest++;
      }
      src++;
    }
    //  at this point, dest gives the new end of the array
    

    Just to be really silly (but theoretically correct), I'll also point out that the space requirement is still O(1) even if the array holds 64-bit integers. The constant term is a bit big, I agree, and you may have issues with 64-bit CPUs that can't actually use the full 64 bits of an address, but...

提交回复
热议问题