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

Kiểm tra HashSet và tập hợp chỉ định có phần tử chung trong C#

Giới thiệu

Phương thức Overlaps(IEnumerable<T> other) của HashSet<T> kiểm tra xem tập hợp hiện tại và tập hợp chỉ định có chia sẻ ít nhất một phần tử chung hay không. Trả về true nếu có giao nhau, false nếu không giao nhau.

Ví dụ 1

using System;
using System.Collections.Generic;

public class Demo
{
    public static void Main()
    {
        HashSet set1 = new HashSet();
        set1.Add(25);
        set1.Add(50);
        set1.Add(75);
        set1.Add(100);
        set1.Add(125);
        set1.Add(150);

        Console.WriteLine("Các phần tử trong HashSet1:");
        foreach (int val in set1)
        {
            Console.WriteLine(val);
        }

        HashSet set2 = new HashSet();
        set2.Add(30);
        set2.Add(60);
        set2.Add(100);
        set2.Add(150);
        set2.Add(200);
        set2.Add(250);

        Console.WriteLine("Các phần tử trong HashSet2:");
        foreach (int val in set2)
        {
            Console.WriteLine(val);
        }

        Console.WriteLine("Hai tập hợp có phần tử chung? = " + set1.Overlaps(set2));
    }
}

Kết quả

Các phần tử trong HashSet1
25
50
75
100
125
150
Các phần tử trong HashSet2
30
60
100
150
200
250
Hai tập hợp có phần tử chung? = True

Ví dụ 2

using System;
using System.Collections.Generic;

public class Demo
{
    public static void Main()
    {
        HashSet set1 = new HashSet();
        set1.Add("Nathan");
        set1.Add("Tim");
        set1.Add("Tom");
        set1.Add("Jack");
        set1.Add("Steve");
        set1.Add("David");

        Console.WriteLine("Các phần tử trong HashSet1:");
        foreach (string val in set1)
        {
            Console.WriteLine(val);
        }

        HashSet set2 = new HashSet();
        set2.Add("Tom");
        set2.Add("Jack");
        set2.Add("Kevin");

        Console.WriteLine("Các phần tử trong HashSet2:");
        foreach (string val in set2)
        {
            Console.WriteLine(val);
        }

        Console.WriteLine("Hai tập hợp có phần tử chung? = " + set1.Overlaps(set2));
    }
}

Kết quả

Các phần tử trong HashSet1
Nathan
Tim
Tom
Jack
Steve
David
Các phần tử trong HashSet2
Tom
Jack
Kevin
Hai tập hợp có phần tử chung? = True

Lưu ý quan trọng

  • Overlaps() trả về true ngay khi tìm thấy phần tử chung đầu tiên (short-circuit).
  • Độ phức tạp trung bình O(min(n, m)) với n, m là kích thước hai tập hợp.
  • Tham số other có thể là bất kỳ IEnumerable<T> nào (List, Array, HashSet khác...).
  • Các phương thức tập hợp liên quan: SetEquals(), IsSubsetOf(), IsProperSubsetOf(), IsSupersetOf(), IsProperSupersetOf(), UnionWith(), IntersectWith(), ExceptWith(), SymmetricExceptWith().