如何在C#中找出两个数组的不匹配元素并按升序排列?
在C#中实现数组差集并保持升序的方法
嘿,这个需求其实就是求两个数组的差集——也就是从第一个数组x里筛选出所有不存在于第二个数组y中的元素,同时保证结果升序排列。下面我给你两种常用的实现方式:
方法一:用LINQ(最简洁高效)
C#的LINQ自带了Except方法,专门用来处理集合差集的场景,而且默认会保留源集合的顺序(刚好你的x本身就是升序的,结果自然符合要求)。代码写起来特别简洁:
using System; using System.Linq; class Program { static void Main() { int[] x = { 0, 1, 2, 3, 4 }; int[] y = { 1, 3, 4 }; // 计算差集并转成数组 int[] z = x.Except(y).ToArray(); // 输出结果看看 Console.WriteLine(string.Join(", ", z)); // 输出: 0, 2 } }
小提醒:如果你的x数组是无序的,想要结果强制升序,只需要在后面加个OrderBy就行:
int[] z = x.Except(y).OrderBy(num => num).ToArray();
方法二:不用LINQ(手动实现)
要是你不想依赖LINQ,也可以手动写逻辑来实现,这里推荐用HashSet来优化查找效率:
using System; using System.Collections.Generic; class Program { static void Main() { int[] x = { 0, 1, 2, 3, 4 }; int[] y = { 1, 3, 4 }; // 把y转成HashSet,这样查找元素的速度会快很多 HashSet<int> yElements = new HashSet<int>(y); List<int> resultList = new List<int>(); // 遍历x的每个元素,筛选不在y里的 foreach (int num in x) { if (!yElements.Contains(num)) { resultList.Add(num); } } int[] z = resultList.ToArray(); Console.WriteLine(string.Join(", ", z)); // 输出: 0, 2 } }
为啥用HashSet?因为它的Contains方法时间复杂度是O(1),比直接用数组的Array.IndexOf(O(n))效率高多了,尤其是当数组元素很多的时候,差距会很明显。
内容的提问来源于stack exchange,提问作者user13957010
相关产品推荐
相关产品推荐

