
共有以下三种方法 -
第一种方法
使用公式n(n+1)/2 计算元素数量,然后需要从数组中的元素中减去。
在第二种方法中
创建一个新数组,遍历整个数组,将找到的数字设为 false。
在第三种方法中强>
使用异或运算。这给出了缺失的数字。
实时演示
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
以上就是使用 C# 在没有任何内置函数的情况下查找排序数组中缺失的数字有哪些不同方法?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号