Computer >> คอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

จะค้นหาหมายเลขที่หายไปและหมายเลขซ้ำในอาร์เรย์ที่เรียงลำดับโดยไม่ต้องใช้ฟังก์ชัน inbuilt โดยใช้ C # ได้อย่างไร


เพื่อค้นหาหมายเลขที่หายไป

สร้างอาร์เรย์ใหม่และสำรวจทั่วทั้งอาร์เรย์ และทำให้ตัวเลขเป็นจริงในอาร์เรย์ใหม่ หากพบตัวเลข เลื่อนผ่านอาร์เรย์ทั้งหมดและคืนค่าองค์ประกอบเท็จตัวแรกเป็นองค์ประกอบที่ขาดหายไป

เพื่อค้นหาองค์ประกอบที่เกิดซ้ำ

องค์ประกอบจริงตัวแรกจากอาร์เรย์ใหม่จะเป็นองค์ประกอบที่ซ้ำกัน

ตัวอย่าง

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