누락된 번호를 찾으려면
새 배열을 만들고 전체 배열을 탐색하고 숫자가 발견되면 새 배열에서 숫자를 true로 만듭니다. 전체 배열을 탐색하고 첫 번째 false 요소를 누락된 요소로 반환합니다.
반복되는 요소를 찾으려면
새 배열의 첫 번째 true 요소는 반복 요소가 됩니다.
예시
using System;
namespace ConsoleApplication{
public class Arrays{
public void MissingNumberAndRepeatedNumber(int[] arr){
bool[] tempArray = new bool[arr.Length + 1];
int missingelement = -1;
int repeatingelement = -1;
for (int i = 0; i < arr.Length; i++){
int index = arr[i];
if (!tempArray[index]){
tempArray[index] = true;
}
};
for (int i = 0; i < tempArray.Length; i++){
if (!tempArray[i]){
missingelement = i;
break;
}
}
int[] tempArray1 = new int[arr.Length + 1];
for (int i = 0; i < arr.Length; i++){
int index = arr[i];
if (tempArray1[index]==0){
tempArray1[index] = 1;
}else if (tempArray1[index]==1){
tempArray1[index] = 2;
}
};
for (int i = 0; i < tempArray1.Length; i++){
if (tempArray1[i]==2){
repeatingelement = i;
break;
}
}
Console.WriteLine(missingelement);
Console.WriteLine(repeatingelement);
}
}
class Program{
static void Main(string[] args){
Arrays a = new Arrays();
int[] arr = { 0, 1, 1, 3, 4 };
a.MissingNumberAndRepeatedNumber(arr);
Console.ReadLine();
}
}
} 출력
2 1