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
- public static int[] NoDuplicate1(int[] arr)
- {
- var map = new HashSet<int>();
- foreach (var i in arr)
- map.Add(i);
- return map.ToArray();
- }
- public static int[] NoDuplicate2(int[] arr)
- {
- var map = new Queue<int>();
- foreach (var i in arr)
- if (!map.Contains(i))
- map.Enqueue(i);
- return map.ToArray();
- }
And testing:
Code Snippet
- int[] a = { 6,5,4,3,1,2,1, 2, 3, 4, 5, 6, 5, 6 };
- var test = Questions.NoDuplicate1(a);
- foreach (var i in test)
- {
- Console.WriteLine(i);
- }
- test = Questions.NoDuplicate2(a);
- foreach (var i in test)
- {
- Console.WriteLine(i);
- }
Both approaches had the sequence maintained of the first integer found in the array.
Comments
Post a Comment