比如给一个 2 2 0 3 4 3 2 6 0 8 6 输出不重复项为2 0 3 4 6 8 要用算法来解决这个问题,完全做不出来~
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,8
2.使用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();
}
}
}
可以排序或者哈希