开发者

Remove duplicate array elements in C [duplicate]

This question already has answers here: Closed 12 years ago.

Possible Duplicate:

remove duplicate elements in an array in O(n) in C/C++

How can I remove duplicate elements from an array?

Before

array [ ] = {1,2,开发者_StackOverflow中文版3,4,5,1,2,4,9,0,0}

After

array [ ] = {0,1,2,3,4,5,9}


  1. Sort the array using your favorite sorting algorithm.

  2. Walk through the array and eliminate duplicates - if a value is the same one as the previous one, keep going forward until you get a new value and then copy it back.


Use hash table and store each element into hash table. This way you will remove duplicates. This will give you O(n) complexity but you will have to add hash table support.


Given that you have an array of integers, and that you know their exact bounds, you can create a lookup table with a single pass over the input (use a bit vector if you have to constrict space) and then generate the array of unique entries with a single pass over the lookup table.

This would be a VERY SPECIFIC solution for a VERY SPECIFIC problem, but it does what you ask for.


memset(index,0,sizeof(index));
for (int i=0; i<len(array); ++i)
   index[array[i]] = 1;
memset(array,0,sizeof(array));
for (int i=0,int j=0; i<len(index); ++i)
   if (index[i]) array[j++] = i;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜