In duplicate từ List
Ví dụ minh họa
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
int[] arr = { 3, 6, 3, 8, 9, 2, 2 };
Console.WriteLine("Mảng: " + string.Join(", ", arr));
// Cách 1: Dictionary
var counts = new Dictionary();
foreach (int x in arr)
counts[x] = counts.GetValueOrDefault(x) + 1;
Console.WriteLine("\nTần suất tất cả:");
foreach (var kvp in counts.OrderBy(k => k.Key))
Console.WriteLine($"{kvp.Key}: {kvp.Value} lần");
Console.WriteLine("\nChỉ phần tử trùng (Count > 1):");
foreach (var kvp in counts.Where(k => k.Value > 1).OrderBy(k => k.Key))
Console.WriteLine($"{kvp.Key} xuất hiện {kvp.Value} lần");
// Cách 2: LINQ GroupBy
Console.WriteLine("\nLINQ GroupBy:");
var duplicates = arr.GroupBy(x => x)
.Where(g => g.Count() > 1)
.Select(g => new { Value = g.Key, Count = g.Count() })
.OrderBy(x => x.Value);
foreach (var d in duplicates)
Console.WriteLine($"{d.Value}: {d.Count} lần");
// Cách 3: HashSet theo dõi seen/duplicate
Console.WriteLine("\nHashSet tracking:");
var seen = new HashSet();
var dupes = new HashSet();
foreach (int x in arr)
{
if (!seen.Add(x)) dupes.Add(x);
}
Console.WriteLine("Phần tử trùng: " + string.Join(", ", dupes.OrderBy(x => x)));
}
}
Kết quả đầu ra
Mảng: 3, 6, 3, 8, 9, 2, 2 Tần suất tất cả: 2: 2 lần 3: 2 lần 6: 1 lần 8: 1 lần 9: 1 lần Chỉ phần tử trùng (Count > 1): 2: 2 lần 3: 2 lần LINQ GroupBy: 2: 2 lần 3: 2 lần HashSet tracking: Phần tử trùng: 2, 3
Hiệu năng: Dictionary/HashSet O(n). GroupBy O(n) nhưng allocation nhiều hơn. HashSet tracking chỉ lưu duplicate, tiết kiệm memory.