OneCompiler

Intersection of two arrays

152
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

namespace OneCompiler
{
	public class Program
	{
		public static void Main(string[] args)
		{
			int m = int.Parse(Console.ReadLine());
			
			int[] arr1 = Array.ConvertAll(Console.ReadLine().Split(" "), new Converter<string,int>(StringToInteger));
			
			int n = int.Parse(Console.ReadLine());
			
			int[] arr2 = Array.ConvertAll(Console.ReadLine().Split(" "), new Converter<string,int>(StringToInteger));
			
			int[] arr3 = Intersection(arr1, arr2);
			
			for (int i = 0; i < arr3.Length; i++)
			{
			  Console.Write(arr3[i] + " ");
			}
		}
		
		private static int StringToInteger(string s)
		{
		  return int.Parse(s);
		}
		
		private static int[] Intersection(int[] arr1, int[] arr2)
		{
		  int m = arr1.Length;
		  int n = arr2.Length;
		  
		  HashSet<int> intersection = new HashSet<int>();
		  
		  int i = 0;
		  int j = 0;
		  
		  while (i < m && j < n)
		  {
		    if (arr1[i] < arr2[j])
		    {
		      i++;
		    }
		    else if(arr1[i] > arr2[j])
		    {
		      j++;
		    }
		    else
		    {
		      intersection.Add(arr1[i]);
		      i++;
		      j++;
		    }
		  }
		  
		  return intersection.ToArray();
		}
	}
}