본문 바로가기
프로그래밍 문제/c# 문제

c# 문제 54. 배열의 교집합 요소 찾기

by 지나팩 2023. 12. 14.

두 개의 정수 배열이 주어졌을 때, 두 배열의 교집합을 찾는 코드를 작성하세요.

 int[] array1 = { 1, 3, 5, 7, 9 };
 int[] array2 = { 3, 6, 7, 8, 9 };

 

출력 예)

코드는 아래에~~~~~~~~~~~~~~~~~~~~~

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
using System;
using System.Collections.Generic;
 
class IntersectArrays
{
    static void Main(string[] args)
    {
        int[] array1 = { 13579 };
        int[] array2 = { 36789 };
 
        HashSet<int> set = new HashSet<int>(array1);
        List<int> intersection = new List<int>();
 
        foreach (int element in array2)
        {
            if (set.Contains(element))
            {
                intersection.Add(element);
            }
        }
 
        Console.WriteLine("교집합:");
        foreach (int element in intersection)
        {
            Console.Write(element + " ");
        }
    }
}
 
cs

댓글