Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Tìm phần tử chung của 3 mảng dùng HashSet C#

Tìm giao của 3 mảng: dùng HashSet.IntersectWith hoặc LINQ Intersect. Hiệu năng O(n) với HashSet.

Ví dụ minh họa

using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
        int[] arr1 = { 99, 57, 63, 98 };
        int[] arr2 = { 43, 99, 33, 57 };
        int[] arr3 = { 99, 57, 42 };
        
        Console.WriteLine("Mảng 1: " + string.Join(", ", arr1));
        Console.WriteLine("Mảng 2: " + string.Join(", ", arr2));
        Console.WriteLine("Mảng 3: " + string.Join(", ", arr3));
        
        // Cách 1: LINQ Intersect (chain)
        var common = arr1.Intersect(arr2).Intersect(arr3);
        Console.WriteLine("\nLINQ Intersect: " + string.Join(", ", common));
        
        // Cách 2: HashSet (hiệu năng tốt, sửa đổi tập gốc)
        var set1 = new HashSet(arr1);
        var set2 = new HashSet(arr2);
        var set3 = new HashSet(arr3);
        
        set1.IntersectWith(set2);
        set1.IntersectWith(set3);
        Console.WriteLine("HashSet IntersectWith: " + string.Join(", ", set1));
        
        // Cách 3: HashSet + Any (chỉ check có giao không)
        bool hasCommon = arr1.Any(x => arr2.Contains(x) && arr3.Contains(x));
        Console.WriteLine($"Có phần tử chung? {hasCommon}");
    }
}

Kết quả đầu ra

Mảng 1: 99, 57, 63, 98
Mảng 2: 43, 99, 33, 57
Mảng 3: 99, 57, 42

LINQ Intersect: 99, 57
HashSet IntersectWith: 99, 57
Có phần tử chung? True

Phức tạp: HashSet O(n+m+k) time, O(n+m+k) space. LINQ Intersect dùng HashSet nội bộ nên tương tự. Code gốc dùng 3 con trỏ (yêu cầu mảng đã sort) - phức tạp hơn, dễ sai.