먼저, 3개의 정렬된 배열을 초기화합니다. −
int []one = {20, 35, 57, 70};
int []two = {9, 35, 57, 70, 92};
int []three = {25, 35, 55, 57, 67, 70}; 세 가지 정렬된 배열에서 공통 요소를 찾으려면 while 루프를 사용하여 배열을 반복하고 첫 번째 배열은 두 번째 배열로, 두 번째 배열은 세 번째 −
로 확인합니다.while (i < one.Length && j < two.Length && k < three.Length) {
if (one[i] == two[j] && two[j] == three[k]) {
Console.Write(one[i] + " ");
i++;j++;k++;
}
else if (one[i] < two[j])
i++;
else if (two[j] < three[k])
j++;
else
k++;
} 예시
다음 코드를 실행하여 세 가지 정렬된 배열에서 공통 요소를 찾을 수 있습니다.
using System;
class Demo {
static void commonElements(int []one, int []two, int []three) {
int i = 0, j = 0, k = 0;
while (i < one.Length && j < two.Length && k < three.Length) {
if (one[i] == two[j] && two[j] == three[k]) {
Console.Write(one[i] + " ");
i++;j++;k++;
}
else if (one[i] < two[j])
i++;
else if (two[j] < three[k])
j++;
else
k++;
}
}
public static void Main() {
int []one = {20, 35, 57, 70};
int []two = {9, 35, 57, 70, 92};
int []three = {25, 35, 55, 57, 67, 70};
Console.Write("Common elements: ");
commonElements(one, two, three);
}
} 출력
Common elements: 35 57 70