Home >Backend Development >C#.Net Tutorial >What are the different ways to find missing numbers in a sorted array using C# without any built-in functions?

What are the different ways to find missing numbers in a sorted array using C# without any built-in functions?

WBOY
WBOYforward
2023-08-29 15:45:061308browse

使用 C# 在没有任何内置函数的情况下查找排序数组中缺失的数字有哪些不同方法?

There are three methods-

  • The first method

    use the formula n( n 1)/2 counts the number of elements, which then need to be subtracted from the elements in the array.

  • In the second method

    Create a new array, iterate through the entire array, and set the found numbers to false.

  • In the third method强>

    use XOR operation. This gives the missing number.

Example

Real-time demonstration

using System;
namespace ConsoleApplication{
   public class Arrays{
      public int MissingNumber1(int[] arr){
         int totalcount = 0;
         for (int i = 0; i < arr.Length; i++){
            totalcount += arr[i];
         }
         int count = (arr.Length * (arr.Length + 1)) / 2;
         return count - totalcount;
      }
      public int MissingNumber2(int[] arr){
         bool[] tempArray = new bool[arr.Length + 1];
         int element = -1;
         for (int i = 0; i < arr.Length; i++){
            int index = arr[i];
            tempArray[index] = true;
         }
         for (int i = 0; i < tempArray.Length; i++){
            if (tempArray[i] == false){
               element = i;
               break;
            }
         }
         return element;
      }
      public int MissingNumber3(int[] arr){
         int result = 1;
         for (int i = 0; i < arr.Length; i++){
            result = result ^ arr[i];
         }
         return result;
      }
   }
   class Program{
      static void Main(string[] args){
         Arrays a = new Arrays();
         int[] arr = { 0, 1, 3, 4, 5 };
         Console.WriteLine(a.MissingNumber1(arr));
         Console.WriteLine(a.MissingNumber2(arr));
         Console.WriteLine(a.MissingNumber3(arr));
         Console.ReadLine();
      }
   }
}

Output

2
2
2

The above is the detailed content of What are the different ways to find missing numbers in a sorted array using C# without any built-in functions?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete