Tech Qu: Removing duplicates from an integer array

Write two algorithms to remove duplicates from an integer array.

 

There are many solutions including sorting the array and then finding duplicates. My preference would be the following ones

Code Snippet
  1. public static int[] NoDuplicate1(int[] arr)
  2. {
  3.   var map = new HashSet<int>();
  4.   foreach (var i in arr)
  5.     map.Add(i);
  6.   return map.ToArray();
  7. }
  8. public static int[] NoDuplicate2(int[] arr)
  9. {
  10.   var map = new Queue<int>();
  11.   foreach (var i in arr)
  12.     if (!map.Contains(i))
  13.       map.Enqueue(i);
  14.   return map.ToArray();
  15. }

 

And testing:

Code Snippet
  1. int[] a = { 6,5,4,3,1,2,1, 2, 3, 4, 5, 6, 5, 6 };      
  2. var test = Questions.NoDuplicate1(a);
  3. foreach (var i in test)
  4. {
  5.   Console.WriteLine(i);
  6. }
  7. test = Questions.NoDuplicate2(a);
  8. foreach (var i in test)
  9. {
  10.   Console.WriteLine(i);
  11. }

 

Both approaches had the sequence maintained of the first integer found in the array.

image

Comments

Popular posts from this blog

Yet once more into the breech (of altered programming logic)

Simple WP7 Mango App for Background Tasks, Toast, and Tiles: Code Explanation

How to convert SVG data to a Png Image file Using InkScape