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.
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(); } } }
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!