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

WBOY
Release: 2023-08-29 15:45:06
forward
1275 people have browsed it

使用 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();
      }
   }
}
Copy after login

Output

2
2
2
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template