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

Kiểm tra SortedSet và tập hợp có phần tử chung trong C#

Giới thiệu

Phương thức Overlaps(IEnumerable<T>) của SortedSet<T> kiểm tra xem có ít nhất một phần tử chung giữa hai tập hợp hay không. Trả về true nếu có giao nhau, ngược lại false.

Ví dụ 1: Hai tập hợp có phần tử chung

using System;
using System.Collections.Generic;

public class Demo
{
    public static void Main()
    {
        SortedSet<int> set1 = new SortedSet<int>();
        set1.Add(100);
        set1.Add(200);
        set1.Add(300);
        set1.Add(400);
        set1.Add(500);
        set1.Add(600);
        
        SortedSet<int> set2 = new SortedSet<int>();
        set2.Add(100);
        set2.Add(200);
        set2.Add(300);
        set2.Add(400);
        set2.Add(500);
        set2.Add(600);
        
        Console.WriteLine("Does it share common elements? = " + set1.Overlaps(set2));
    }
}

Kết quả

Does it share common elements? = True

Ví dụ 2: Hai tập hợp không có phần tử chung

using System;
using System.Collections.Generic;

public class Demo
{
    public static void Main()
    {
        SortedSet<int> set1 = new SortedSet<int>();
        set1.Add(100);
        set1.Add(200);
        set1.Add(300);
        
        SortedSet<int> set2 = new SortedSet<int>();
        set2.Add(450);
        set2.Add(550);
        set2.Add(650);
        set2.Add(750);
        set2.Add(800);
        
        Console.WriteLine("Does it share common elements? = " + set1.Overlaps(set2));
    }
}

Kết quả

Does it share common elements? = False

Đặc điểm của Overlaps()

  • Phức tạp: O(n) - duyệt qua tập hợp nhỏ hơn
  • Ngừng sớm (short-circuit) khi tìm thấy phần tử chung đầu tiên
  • Chấp nhận bất kỳ IEnumerable<T> nào, không chỉ SortedSet
  • Không thay đổi tập hợp gốc

So sánh với các phương thức liên quan

Phương thức Ý nghĩa Ví dụ
Overlaps Có ít nhất 1 phần tử chung {1,2} & {2,3} → true
SetEquals Cùng phần tử (bằng nhau) {1,2} & {1,2} → true
IsSubsetOf Là tập con {1} & {1,2} → true
IsSupersetOf Là tập cha {1,2} & {1} → true