Tìm duplicate trong mảng int: Dictionary đếm tần suất, hoặc LINQ GroupBy lọc Count > 1.
Ví dụ minh họa
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
int[] arr = { 24, 10, 56, 32, 10, 43, 88, 32 };
Console.WriteLine("Mảng: " + string.Join(", ", arr));
// Cách 1: Dictionary (hiệu năng tốt)
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(x => x.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}: {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");
}
}
Kết quả đầu ra
Mảng: 24, 10, 56, 32, 10, 43, 88, 32 Tần suất tất cả: 10: 2 lần 24: 1 lần 32: 2 lần 43: 1 lần 56: 1 lần 88: 1 lần Chỉ phần tử trùng (Count > 1): 10: 2 lần 32: 2 lần LINQ GroupBy: 10: 2 lần 32: 2 lần
Phức tạp: O(n) time, O(n) space. Dictionary nhanh hơn GroupBy do tránh allocation delegate.