在 C# 中,可以使用特定的集合类型或算法来实现集合的自动去重,并通过优化策略提高去重操作的性能。
C# 中实现集合自动去重的方式
- 使用
HashSet<T>
HashSet<T>
是基于哈希表的集合类型,天然支持存储唯一值。- 添加元素时,如果元素已存在,则不会重复添加。
- 时间复杂度: 平均 (O(1)),最坏情况下 (O(n))(哈希冲突多时)。
- 代码示例:
using System; using System.Collections.Generic; class Program { static void Main() { List<int> numbers = new List<int> { 1, 2, 2, 3, 4, 4, 5 }; HashSet<int> uniqueNumbers = new HashSet<int>(numbers); foreach (var num in uniqueNumbers) { Console.WriteLine(num); } } }
- 输出:
1 2 3 4 5
- 使用
SortedSet<T>
SortedSet<T>
是基于二叉搜索树(红黑树)的集合类型,自动保持元素有序且唯一。- 时间复杂度: 插入和查找操作的时间复杂度为 (O(\log n))。
- 适用场景: 在需要有序且唯一的集合时使用。
- 代码示例:
using System