How to print all elements of an array only once in C#

1 Answer

0 votes
using System;
using System.Collections.Generic; 
					
public class Program
{
	static void printElementsOnlyOnce(int[] arr) { 
        Dictionary<int,int> dict = new Dictionary<int,int>(); 

		for (int i = 0; i < arr.Length; i++) { 
            if (dict.ContainsKey(arr[i])) 
                dict.Remove(arr[i]); 
            dict.Add(arr[i], i); 
        } 
        var keys = dict.Keys; 
        foreach(int n in keys) 
            Console.Write(n + " "); 
	}
	public static void Main()
	{
		int[] arr = { 3, 5, 9, 1, 7, 8, 1, 9, 0, 3, 9, 9, 5, 5, 5 }; 
		
		printElementsOnlyOnce(arr);
	}
}



/*
run:

3 5 9 1 7 8 0

*/

 



answered May 4, 2020 by avibootz

Related questions

1 answer 148 views
1 answer 168 views
1 answer 150 views
1 answer 185 views
1 answer 158 views
1 answer 103 views
1 answer 128 views
...