共有以下三种方法 -
-
第一种方法
使用公式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# 在没有任何内置函数的情况下查找排序数组中缺失的数字有哪些不同方法?的详细内容,更多请关注编程之家其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。