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

WBOY
发布: 2023-08-29 15:45:06
转载
1250 人浏览过

使用 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# 在没有任何内置函数的情况下查找排序数组中缺失的数字有哪些不同方法?的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:tutorialspoint.com
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!