Remove Duplicates from Unsorted Array - CSharp System

CSharp examples for System:Array Operation

Description

Remove Duplicates from Unsorted Array

Demo Code


using System.Collections.Generic;
using System;/*  w w  w . j  a  v  a  2 s . c om*/

public class Main{
        public static T[] RemoveDuplicatesUnsorted<T>(T[] array)
        {
            var set = new HashSet<T>();
            int offset = 0;

            for (int i = 0; i < array.Length; ++i)
            {
                if (set.Contains(array[i]))
                {
                    offset++;
                }
                else
                {
                    set.Add(array[i]);
                    array[i - offset] = array[i];
                }
            }

            T[] copyArray = new T[array.Length - offset];
            Array.Copy(array, copyArray, array.Length - offset);
            return copyArray;
        }
}

Related Tutorials