remove duplicate element in an array
demonstrates an O(n2) method to remove the duplicated elements in an array
// caution: 1. don't try to return int[] array from a function, c++ doesn't support this, though c# does it well.
// 2. when passing an array to a function, also pass along the length, since in the scope of the function, the array is treated as point in the eye of compiler
// 3. when return a newly created array in the function, also return the lengh of the array, since you could only return a point
// 4. good luck!!!
#include "stdafx.h"
#include "windows.h"
#include "malloc.h"
int RemoveDuplicate(int* dupList, int ilenDupList, int** ppuniqueList);
int _tmain(int argc, _TCHAR* argv[])
{
int dupList[] = {2, 3, 5, 7, 9, 10, 2, 5};
int ilenDupList = sizeof(dupList) / sizeof(int);
int* puniqueList;
int ilenUniqueList = RemoveDuplicate(dupList, ilenDupList, &puniqueList);
for(int i=0; i<ilenUniqueList; i++)
{
printf("%d ", puniqueList[i]);
}
return 0;
}
int RemoveDuplicate(int* dupList, int ilenDupList, int** ppuniqueList)
{
if(dupList == NULL)
{
(*ppuniqueList) = NULL;
return 0;
}
int* deletedMark = (int *)malloc( ilenDupList*sizeof(int) );
ZeroMemory(deletedMark, ilenDupList*sizeof(int));
//
// Loop through to mark the duplicated elements in list: deletedMark
//
for(int i=0; i<ilenDupList; i++)
{
if( deletedMark[i]!=1 )
{
for(int j=i+1; j<ilenDupList; j++)
{
if(deletedMark[j]!=1)
{
if( dupList[i] == dupList[j] )
{
deletedMark[j] = 1;
}
}
}
}
}
//
// Copy the unique element
//
// 1. measure the num of unique elem
int inumUniqueElem = 0;
for(int uniqueIndex=0; uniqueIndex<ilenDupList; uniqueIndex++)
{
if(deletedMark[uniqueIndex]!=1)
{
inumUniqueElem++;
}
}
// 2. copy the unique elem to the result list
int* puniqueList = (int*) malloc(inumUniqueElem*sizeof(int));
int uniqueListIndex = 0;
for(int dupListIndex=0; dupListIndex<ilenDupList; dupListIndex++)
{
if(deletedMark[dupListIndex]!=1)
{
puniqueList[uniqueListIndex++] = dupList[dupListIndex];
}
}
(*ppuniqueList) = puniqueList;
free(deletedMark);
return inumUniqueElem;
}