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

Lấy giá trị nhỏ nhất trong SortedSet C#

Giới thiệu

Thuộc tính Min của SortedSet<T> trả về phần tử nhỏ nhất (theo thứ tự sắp xếp). Max trả về lớn nhất. Cả hai đều O(1) nhờ cấu trúc cây cân bằng.

Ví dụ 1: SortedSet Min/Max

using System;
using System.Collections.Generic;

public class Demo
{
    public static void Main()
    {
        SortedSet set1 = new SortedSet();
        set1.Add("AB");
        set1.Add("BC");
        set1.Add("CD");
        set1.Add("EF");

        Console.WriteLine("Các phần tử SortedSet1...");
        foreach (string res in set1)
        {
            Console.WriteLine(res);
        }
        Console.WriteLine("Phần tử lớn nhất SortedSet1 = " + set1.Max);
        Console.WriteLine("Phần tử nhỏ nhất SortedSet1 = " + set1.Min);

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

        Console.WriteLine("Các phần tử SortedSet2 (Enumerator)...");
        SortedSet.Enumerator demoEnum = set2.GetEnumerator();
        while (demoEnum.MoveNext())
        {
            string res = demoEnum.Current;
            Console.WriteLine(res);
        }
        Console.WriteLine("Phần tử lớn nhất SortedSet2 = " + set2.Max);
        Console.WriteLine("Phần tử nhỏ nhất SortedSet2 = " + set2.Min);
    }
}

Kết quả

Các phần tử SortedSet1...
AB
BC
CD
EF
Phần tử lớn nhất SortedSet1 = EF
Phần tử nhỏ nhất SortedSet1 = AB
Các phần tử SortedSet2 (Enumerator)...
AB
BC
CD
DE
EF
HI
JK
Phần tử lớn nhất SortedSet2 = JK
Phần tử nhỏ nhất SortedSet2 = AB

Ví dụ 2: SortedSet Min/Max

using System;
using System.Collections.Generic;

public class Demo
{
    public static void Main()
    {
        SortedSet set1 = new SortedSet();
        set1.Add(5);
        set1.Add(50);
        set1.Add(20);
        set1.Add(10);
        set1.Add(70);
        set1.Add(60);
        set1.Add(55);
        set1.Add(95);

        Console.WriteLine("Các phần tử SortedSet...");
        foreach (int res in set1)
        {
            Console.WriteLine(res);
        }
        Console.WriteLine("Phần tử lớn nhất SortedSet = " + set1.Max);
        Console.WriteLine("Phần tử nhỏ nhất SortedSet = " + set1.Min);
    }
}

Kết quả

Các phần tử SortedSet...
5
10
20
50
55
60
70
95
Phần tử lớn nhất SortedSet = 95
Phần tử nhỏ nhất SortedSet = 5

Lưu ý

  • Nếu SortedSet rỗng, truy cập Min/Max ném InvalidOperationException.
  • Kiểm tra Count > 0 trước khi truy cập.
  • Có thể dùng GetViewBetween(lower, upper) để lấy tập con trong khoảng.