Computer >> 컴퓨터 >  >> 프로그래밍 >> C#

C# SortedSet에 특정 요소가 포함되어 있는지 확인하는 방법

C#에서 SortedSet<T> 컬렉션에 특정 요소가 포함되어 있는지 확인하려면 Contains() 메서드를 사용하면 됩니다. 이 메서드는 지정한 요소가 집합에 존재하면 true, 존재하지 않으면 false를 반환합니다.

또한 SortedSet은 중복 요소를 허용하지 않으므로, 같은 값을 여러 번 추가해도 한 번만 저장된다는 점을 참고하세요.

예제 1 – 문자열 SortedSet

using System;
using System.Collections.Generic;

public class Demo {
   public static void Main() {
      SortedSet<string> set1 = new SortedSet<string>();
      set1.Add("CD");
      set1.Add("CD");
      set1.Add("CD");
      set1.Add("CD");

      Console.WriteLine("Elements in SortedSet1...");
      foreach (string res in set1) {
         Console.WriteLine(res);
      }

      Console.WriteLine("Does the SortedSet1 contains the element DE? = " + set1.Contains("DE"));

      SortedSet<string> set2 = new SortedSet<string>();
      set2.Add("BC");
      set2.Add("CD");
      set2.Add("DE");
      set2.Add("EF");
      set2.Add("AB");
      set2.Add("HI");
      set2.Add("JK");

      Console.WriteLine("Elements in SortedSet2...");
      foreach (string res in set2) {
         Console.WriteLine(res);
      }

      Console.WriteLine("SortedSet2 is a superset of SortedSet1? = " + set2.IsSupersetOf(set1));
   }
}

출력 결과

Elements in SortedSet1...
CD
Does the SortedSet1 contains the element DE? = False
Elements in SortedSet2...
AB
BC
CD
DE
EF
HI
JK
SortedSet2 is a superset of SortedSet1? = True

위 예제에서 set1에는 "CD"가 여러 번 추가되었지만, 집합(set)의 특성상 중복이 제거되어 하나의 요소만 저장됩니다. 따라서 Contains("DE")의 호출 결과는 False입니다.

반면 set2에는 "DE"가 포함되어 있고 set1의 모든 요소("CD")를 함께 포함하고 있으므로, IsSupersetOf() 메서드는 True를 반환합니다.

예제 2 – 정수 SortedSet

이번에는 정수형 SortedSet에서 특정 숫자의 포함 여부를 확인해 보겠습니다.

using System;
using System.Collections.Generic;

public class Demo {
   public static void Main() {
      SortedSet<int> mySet = new SortedSet<int>();
      mySet.Add(100);
      mySet.Add(200);
      mySet.Add(300);
      mySet.Add(400);

      Console.WriteLine("Elements in SortedSet...");
      foreach (int res in mySet) {
         Console.WriteLine(res);
      }

      Console.WriteLine("Does the SortedSet contains the element 400? = " + mySet.Contains(400));
   }
}

출력 결과

Elements in SortedSet...
100
200
300
400
Does the SortedSet contains the element 400? = True

정리

  • Contains(T item): SortedSet에 해당 요소가 존재하면 true, 존재하지 않으면 false를 반환합니다.
  • SortedSet은 내부적으로 균형 이진 검색 트리(레드-블랙 트리) 구조로 구현되어 있어, Contains 메서드는 O(log n)의 시간 복잡도로 빠르게 동작합니다.
  • SortedSet은 항상 정렬된 상태를 유지하며, 중복된 요소는 자동으로 제거됩니다.