두 개의 정수 배열이 주어졌을 때, 두 배열의 교집합을 찾는 코드를 작성하세요.
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 = { 1, 3, 5, 7, 9 };
int[] array2 = { 3, 6, 7, 8, 9 };
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 |
'프로그래밍 문제 > c# 문제' 카테고리의 다른 글
c# 문제 56. 주어진 정수형 배열의 범위 중 빠진 숫자들 찾기 (1) | 2024.01.29 |
---|---|
c# 문제 55. 배열에서 두 요소의 합이 특정 값이 되는 모든 요소 쌍 찾기 (1) | 2023.12.15 |
c# 문제 53. 배열의 요소 무작위 정렬 (0) | 2023.12.13 |
c# 문제 52. 보물 찾기 게임 (0) | 2023.12.12 |
c# 문제 51. 가위 바위 보 (0) | 2023.12.01 |
댓글