比如给一个 2 2 0 3 4 3 2 6 0 8 6 输出不重复项为2 0 3 4 6 8 要用算法来解决这个问题,完全做不出来~
2条回答 默认 最新
码老头 2022-01-10 21:27关注C#可以有多种实现方式:
1.最简单的方式,使用LINQ的静态扩展方法Distinct(),示例如下:using System; using System.Linq; namespace ConsoleApp1 { class Program { static void Main(string[] args) { var arr = new[] { 2, 2, 0, 3, 4, 3, 2, 6, 0, 8, 6 }; var result = arr.Distinct().ToArray(); Console.WriteLine(string.Join(",", result)); Console.ReadKey(); } } }运行结果:
2,0,3,4,6,82.使用HashSet,示例如下:
using System; using System.Collections.Generic; namespace ConsoleApp1 { class Program { static void Main(string[] args) { var arr = new[] { 2, 2, 0, 3, 4, 3, 2, 6, 0, 8, 6 }; var set = new HashSet<int>(arr); var result = new int[set.Count]; set.CopyTo(result); Console.WriteLine(string.Join(",", result)); Console.ReadKey(); } } }3.使用ArrayList临时存储,示例如下:
using System; using System.Collections; namespace ConsoleApp1 { class Program { static void Main(string[] args) { var arr = new[] { 2, 2, 0, 3, 4, 3, 2, 6, 0, 8, 6 }; var temp = new ArrayList(); foreach (var t in arr) { if (!temp.Contains(t)) { temp.Add(t); } } var result = temp.ToArray(); Console.WriteLine(string.Join(",", result)); Console.ReadKey(); } } }本回答被题主选为最佳回答 , 对您是否有帮助呢?解决评论 打赏 举报无用 1