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

2023年 8月 29日 32.2k 0

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

共有以下三种方法 -

  • 第一种方法

    使用公式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# 在没有任何内置函数的情况下查找排序数组中缺失的数字有哪些不同方法?的详细内容,更多请关注每日运维网(www.mryunwei.com)其它相关文章!

相关文章

JavaScript2024新功能:Object.groupBy、正则表达式v标志
PHP trim 函数对多字节字符的使用和限制
新函数 json_validate() 、randomizer 类扩展…20 个PHP 8.3 新特性全面解析
使用HTMX为WordPress增效:如何在不使用复杂框架的情况下增强平台功能
为React 19做准备:WordPress 6.6用户指南
如何删除WordPress中的所有评论

发布评论