I am begginner in C# and I need your help on writing a program which will remove the duplicates from an integer array?
I tried but not sure how will I assign Null value to int type?
public void RemoveDuplicates(int[] A){
for (int i = 0, j = A.Length - 1; i <= j; i++, j--){
if (A[i] == A[j]){
A[j] = 0;
}
Console.WriteLine(A[i]);}
}
I also tried using an ArrayList where I will check if the arraylist already contains the element if not add else do nothing.
Thanks for your time in advance
AlanPosted Nov 2, 2008, 11:58 AM
Try this:
public void RemoveDuplicates(ref int[] A)
{
Array.Sort(A);
ArrayList list = new ArrayList(A);
for (int i = list.Count - 1; i > 0; i--)
{
if ((int)list[i] == (int)list[i-1]) list.RemoveAt(i);
}
A = (int[])list.ToArray(typeof(int));
}
Notice that you need to pass the array variable by reference as you're assigning a different array object to it after the duplicates have been removed. The array is also sorted into numeric order as a by product.